建立及排定機密資料保護檢查工作

本主題將詳細說明如何建立 Sensitive Data Protection 檢查工作,以及如何建立工作觸發條件,排定定期檢查工作。如需如何使用 Sensitive Data Protection UI 建立新工作觸發條件的快速逐步操作說明,請參閱「快速入門:建立 Sensitive Data Protection 工作觸發條件」。

關於檢查工作和工作觸發條件

當 Sensitive Data Protection 執行檢查掃描來識別機密資料時,每次掃描都會以工作的形式執行。每當您要求檢查 Google Cloud 儲存空間存放區 (包括 Cloud Storage 值區、BigQuery 表格、Datastore 種類和外部資料) 時,Sensitive Data Protection 就會建立及執行作業資源。

您可以建立工作觸發條件,排定 Sensitive Data Protection 檢查掃描工作。工作觸發條件會定期自動建立 Sensitive Data Protection 工作,也可以依需求執行。

如要進一步瞭解 Sensitive Data Protection 中的工作和工作觸發條件,請參閱「工作和工作觸發條件」概念頁面。

建立新的檢查工作

如要建立新的機密資料保護檢查工作,請按照下列步驟操作:

控制台

在 Google Cloud 控制台的「Sensitive Data Protection」專區中,前往「Create job or job trigger」頁面。

前往「建立工作或工作觸發條件」

「Create job or job trigger」(建立工作或工作觸發條件) 頁面包含下列章節:

選擇輸入資料

名稱

輸入工作名稱。您可以使用英文字母、數字和連字號。您可以選擇是否要為工作命名。如果沒有輸入名稱,Sensitive Data Protection 會為工作指派專屬數字 ID。

位置

從「Storage type」(儲存空間類型) 選單中,選擇用於儲存您要掃描之資料的存放區類型:

  • Cloud Storage:輸入要掃描的值區網址,或從「Location type」(位置類型) 選單中選擇「Include/exclude」(納入/排除),然後按一下「Browse」(瀏覽),前往要掃描的值區或子資料夾。選取「以遞迴方式掃描資料夾」核取方塊,即可掃描指定目錄和所有內含目錄。取消選取該核取方塊可僅掃描指定目錄,而不深入掃描。
  • BigQuery:輸入要掃描的專案、資料集和資料表 ID。
  • Datastore:輸入要掃描的專案、命名空間 (選用) 和種類的 ID。
  • 混合式:您可以新增必要標籤、選用標籤,以及處理表格資料的選項。詳情請參閱「可提供的中繼資料類型」。

取樣

如果您擁有非常龐大的資料量,取樣是一種可節省資源的選擇性方法。

在 [Sampling] (取樣方法) 下,您可以選擇掃描所有選取的資料,還是透過掃描特定百分比來取樣資料。取樣的工作方式會視您掃描的儲存空間存放區類型而有所不同:

  • 針對 BigQuery,您可以取樣所有已選取資料列的子集,並對應於您指定要包含在掃描作業內的檔案百分比。
  • 針對 Cloud Storage,如果任何檔案超出「Max byte size to scan per file」(每個待掃描檔案的位元組大小上限) 中指定的大小,Sensitive Data Protection 最多會掃描至該檔案大小上限,然後移至下一個檔案。

如要開啟取樣,請從第一個選單中選擇下列其中一個選項:

  • 從頭開始取樣:Sensitive Data Protection 會從資料的開頭開始部分掃描。針對 BigQuery,此設定會從第一個資料列開始掃描。針對 Cloud Storage,此設定會從每個檔案的開頭開始掃描,並在 Sensitive Data Protection 掃描到任何指定檔案大小上限之後停止掃描。
  • 隨機開始取樣:Sensitive Data Protection 會從資料的隨機位置開始部分掃描。針對 BigQuery,此設定會從隨機資料列開始掃描。針對 Cloud Storage,此設定僅適用於超出任何指定大小上限的檔案。Sensitive Data Protection 掃描檔案的整體大小會低於檔案大小上限,若高於檔案大小上限,則會掃描到該上限為止。

如要執行部分掃描,您也必須選擇想要掃描的資料百分比。使用滑桿可設定百分比。

您也可以按日期縮小要掃描的檔案或記錄範圍。如需操作方式,請參閱本主題後文的「排程」一節。

進階設定

當您針對 Cloud Storage bucket 或 BigQuery 資料表建立掃描工作時,可指定進階設定來縮小搜尋範圍。具體而言,您可以設定:

  • 檔案 (僅限 Cloud Storage):要掃描的檔案類型,包括文字、二進位檔和圖片檔。
  • 識別欄位 (僅限 BigQuery):表格中的不重複資料列 ID。
  • 針對 Cloud Storage,如果任何檔案超出「Max byte size to scan per file」(每個待掃描檔案的位元組大小上限) 中指定的大小,Sensitive Data Protection 最多會掃描至該檔案大小上限,然後移至下一個檔案。

如要開啟取樣功能,請選擇要掃描的資料百分比。使用滑桿設定百分比。然後從第一個選單中選擇下列其中一個選項:

  • 從頭開始取樣:Sensitive Data Protection 會從資料的開頭開始部分掃描。針對 BigQuery,此設定會從第一個資料列開始掃描。針對 Cloud Storage,此設定會從每個檔案的開頭開始掃描,並在 Sensitive Data Protection 掃描到任何指定檔案大小上限 (請參閱上述說明) 之後停止掃描。
  • 隨機開始取樣:Sensitive Data Protection 會從資料的隨機位置開始部分掃描。針對 BigQuery,此設定會從隨機資料列開始掃描。針對 Cloud Storage,此設定僅適用於超出任何指定大小上限的檔案。Sensitive Data Protection 掃描檔案的整體大小會低於檔案大小上限,若高於檔案大小上限,則會掃描到該上限為止。
檔案

針對儲存在 Cloud Storage 中的檔案,您可以在「Files」(檔案) 下指定要包含在掃描中的類型。

您可以選擇二進位檔、文字、圖片、CSV、TSV、Microsoft Word、Microsoft Excel、 Microsoft PowerPoint、PDF 和 Apache Avro 檔案。如需機密資料保護可在 Cloud Storage 值區中掃描的副檔名完整清單,請參閱 FileType。選擇「二進位檔」會導致 Sensitive Data Protection 掃描無法辨識的檔案類型。

識別欄位

如果是 BigQuery 中的資料表,您可以在「識別欄位」欄位中,指示 Sensitive Data Protection 在結果中加入資料表主鍵欄的值。這麼做可將發現項目連結回包含這些項目的資料表列。

輸入可唯一識別資料表中每個資料列的資料欄名稱。如有需要,請使用點標記法指定巢狀欄位。您可以視需要新增任意數量的欄位。

您也必須開啟「儲存至 BigQuery」動作,才能將發現項目匯出至 BigQuery。將發現項目匯出至 BigQuery 時,每個發現項目都會包含識別欄位的相應值。詳情請參閱 identifyingFields 的說明。

設定偵測作業

「Configure detection」(設定偵測作業) 區段可讓您指定想要掃描的機密資料類型。你可以選擇是否填寫這個部分。如果略過這個部分,Sensitive Data Protection 會掃描資料,找出預設的一組 infoTypes

範本

您可以選擇使用 Sensitive Data Protection 範本,重複使用先前已指定的設定資訊。

如果您已建立要使用的範本,請按一下「範本名稱」欄位,查看現有檢查範本清單。選擇或輸入要使用的範本名稱。

如要進一步瞭解如何建立範本,請參閱建立機密資料保護檢查範本一文。

InfoType

InfoType 偵測工具可尋找特定類型的機密資料。舉例來說,Sensitive Data Protection US_SOCIAL_SECURITY_NUMBER 內建的 infoType 偵測工具可尋找美國社會安全號碼。除了內建的 infoType 偵測工具,您也可以建立自己的自訂 infoType 偵測工具。

在「InfoType」底下,根據您要掃描的資料類型,選擇對應的 infoType 偵測工具。我們不建議將這個部分留空。這麼做會導致 Sensitive Data Protection 使用預設的 infoType 組合掃描資料,其中可能包含您不需要的 infoType。如要進一步瞭解每項偵測工具,請參閱 InfoType 偵測工具參考資料

如要進一步瞭解如何管理這個專區中的內建和自訂 infoType,請參閱透過 Google Cloud 控制台管理 infoType

檢查規則集
可信度門檻

每當敏感資料保護偵測到可能的敏感資料相符項目,就會在「非常不可能」到「非常可能」的範圍內,為該項目指派「可能性」值。在此設定可能性值時,您是在指示 Sensitive Data Protection 只比對符合該可能性值或更高的資料。

預設值「Possible」(或許可能) 足以供大多數情況使用。如果您經常得到過於寬泛的相符項目,請將滑桿上移。如果您得到的相符項目太少,請將滑桿下移。

完成後,按一下 [Continue] (繼續)

新增動作

在「Add actions」(新增動作) 步驟中,選取想讓 Sensitive Data Protection 在工作完成之後執行的一或多個動作。

您可以設定下列動作:

  • 儲存至 BigQuery:將 Sensitive Data Protection 作業結果儲存至 BigQuery 資料表。您必須先確認工作已經完成,才能查看或分析結果。

    每次執行掃描時,Sensitive Data Protection 都會將掃描結果儲存到您指定的 BigQuery 資料表。匯出的發現項目包含每個發現項目位置與相符可能性的詳細資料。如要讓每項發現都包含與 infoType 偵測工具相符的字串,請啟用「Include quote」(包含引號) 選項。

    如果您未指定表格 ID,BigQuery 會在首次執行掃描作業時,為新表格指派預設名稱。如果您指定現有的資料表,Sensitive Data Protection 會將掃描結果附加至該資料表。

    如未將發現項目儲存至 BigQuery,掃描結果只會包含與發現項目的數量和 infoType 相關的統計資料。

    將資料寫入 BigQuery 資料表時,費用與配額用量會計入目的地資料表所屬專案。

  • 發布至 Pub/Sub:將含有 Sensitive Data Protection 工作名稱的通知發布至 Pub/Sub 管道。您可以指定一或多個主題,將通知訊息傳送至這些主題。請確認執行掃描作業的 Sensitive Data Protection 服務帳戶具有主題的發布存取權。

  • 發布至 Security Command Center:將工作結果摘要發布至 Security Command Center。詳情請參閱「將 Sensitive Data Protection 掃描結果傳送至 Security Command Center」。

  • 發布至 Dataplex (已淘汰):將檢查工作結果傳送至 Dataplex Universal Catalog,這是 Google Cloud的中繼資料管理服務。

  • 透過電子郵件通知:作業完成時傳送電子郵件。這封電子郵件會傳送給身分與存取權管理專案擁有者和技術重要聯絡人

  • 發布至 Cloud Monitoring:將檢查結果傳送至 Google Cloud Observability 中的 Cloud Monitoring。

  • 建立去識別化副本:將檢查資料中的所有發現項目去識別化,然後將去識別化內容寫入新檔案。然後,您可以在業務程序中使用去識別化副本,取代含有私密資訊的資料。詳情請參閱「使用 Google Cloud 控制台中的 Sensitive Data Protection,建立 Cloud Storage 資料的去識別化副本」。

詳情請參閱「動作」。

選取動作之後,按一下 [Continue] (繼續)

查看

「Review」(查看) 區段包含您剛指定之工作設定的 JSON 格式摘要。

按一下「建立」即可建立工作 (若您未指定排程),並執行一次工作。隨即會顯示工作的資訊頁面,其中包含狀態及其他資訊。如果目前正在執行工作,您可以按一下「取消」按鈕來停止工作,您也可以按一下「刪除」刪除工作。

如要返回「Sensitive Data Protection」主頁面,請在 Google Cloud 控制台中按一下「返回」箭頭。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using System;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.StorageConfig.Types;

public class JobsCreate
{
    public static DlpJob CreateJob(string projectId, string gcsPath)
    {
        var dlp = DlpServiceClient.Create();

        var storageConfig = new StorageConfig
        {
            CloudStorageOptions = new CloudStorageOptions
            {
                FileSet = new CloudStorageOptions.Types.FileSet()
                {
                    Url = gcsPath
                }
            },
            TimespanConfig = new TimespanConfig
            {
                EnableAutoPopulationOfTimespanConfig = true
            }
        };

        var inspectConfig = new InspectConfig
        {
            InfoTypes = { new[] { "EMAIL_ADDRESS", "CREDIT_CARD_NUMBER" }.Select(it => new InfoType() { Name = it }) },
            IncludeQuote = true,
            MinLikelihood = Likelihood.Unlikely,
            Limits = new InspectConfig.Types.FindingLimits() { MaxFindingsPerItem = 100 }
        };

        var response = dlp.CreateDlpJob(new CreateDlpJobRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            InspectJob = new InspectJobConfig
            {
                InspectConfig = inspectConfig,
                StorageConfig = storageConfig,
            }
        });

        Console.WriteLine($"Job: {response.Name} status: {response.State}");

        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// createJob creates an inspection job
func createJob(w io.Writer, projectID, gcsPath string, infoTypeNames []string) error {
	// projectID := "my-project-id"
	// gcsPath := "gs://" + "your-bucket-name" + "path/to/file.txt";
	// infoTypeNames := []string{"EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER"}

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the GCS file to be inspected.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_CloudStorageOptions{
			CloudStorageOptions: &dlppb.CloudStorageOptions{
				FileSet: &dlppb.CloudStorageOptions_FileSet{
					Url: gcsPath,
				},
			},
		},

		// Set autoPopulateTimespan to true to scan only new content.
		TimespanConfig: &dlppb.StorageConfig_TimespanConfig{
			EnableAutoPopulationOfTimespanConfig: true,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types.
	var infoTypes []*dlppb.InfoType
	for _, c := range infoTypeNames {
		infoTypes = append(infoTypes, &dlppb.InfoType{Name: c})
	}

	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:    infoTypes,
		IncludeQuote: true,

		// The minimum likelihood required before returning a match:
		// See: https://cloud.google.com/dlp/docs/likelihood
		MinLikelihood: dlppb.Likelihood_UNLIKELY,

		// The maximum number of findings to report (0 = server maximum)
		Limits: &dlppb.InspectConfig_FindingLimits{
			MaxFindingsPerItem: 100,
		},
	}

	// Create and send the request.
	req := dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: &dlppb.InspectJobConfig{
				InspectConfig: inspectConfig,
				StorageConfig: storageConfig,
			},
		},
	}

	// Send the request.
	response, err := client.CreateDlpJob(ctx, &req)
	if err != nil {
		return err
	}

	// Print the results.
	fmt.Fprintf(w, "Created a Dlp Job %v and Status is: %v", response.Name, response.State)
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.CloudStorageOptions;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StorageConfig;
import com.google.privacy.dlp.v2.StorageConfig.TimespanConfig;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JobsCreate {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String gcsPath = "gs://" + "your-bucket-name" + "path/to/file.txt";
    createJobs(projectId, gcsPath);
  }

  // Creates a DLP Job
  public static void createJobs(String projectId, String gcsPath) 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()) {

      // Set autoPopulateTimespan to true to scan only new content
      boolean autoPopulateTimespan = true;
      TimespanConfig timespanConfig =
          TimespanConfig.newBuilder()
              .setEnableAutoPopulationOfTimespanConfig(autoPopulateTimespan)
              .build();

      // Specify the GCS file to be inspected.
      CloudStorageOptions cloudStorageOptions =
          CloudStorageOptions.newBuilder()
              .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
              .build();
      StorageConfig storageConfig =
          StorageConfig.newBuilder()
              .setCloudStorageOptions(cloudStorageOptions)
              .setTimespanConfig(timespanConfig)
              .build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());
      // The minimum likelihood required before returning a match:
      // See: https://cloud.google.com/dlp/docs/likelihood
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob createdDlpJob = dlpServiceClient.createDlpJob(createDlpJobRequest);
      System.out.println("Job created successfully: " + createdDlpJob.getName());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Initialize google DLP Client
const dlp = new DLP.DlpServiceClient();

async function jobsCreate() {
  // Construct cloud storage configuration
  const cloudStorageConfig = {
    cloudStorageOptions: {
      fileSet: {
        url: cloudFileUrl,
      },
    },
    timespanConfig: {
      enableAutoPopulationOfTimespanConfig: true,
    },
  };

  // Construct inspect job configuration
  const inspectJob = {
    storageConfig: cloudStorageConfig,
  };

  // Construct inspect configuration
  const inspectConfig = {
    infoTypes: [
      {name: 'EMAIL_ADDRESS'},
      {name: 'PERSON_NAME'},
      {name: 'LOCATION'},
      {name: 'PHONE_NUMBER'},
    ],
    includeQuote: true,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.LIKELY,
    excludeInfoTypes: false,
  };

  // Combine configurations into a request for the service.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: inspectJob,
    inspectConfig: inspectConfig,
  };

  // Send the request and receive response from the service
  const [response] = await dlp.createDlpJob(request);
  // Print the results
  console.log(`Job created successfully: ${response.name}`);
}

jobsCreate();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
use Google\Cloud\Dlp\V2\CreateDlpJobRequest;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\StorageConfig\TimespanConfig;

/**
 * Creates an inspection job with the Cloud Data Loss Prevention API.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $gcsPath           GCS file to be inspected. Example : gs://GOOGLE_STORAGE_BUCKET_NAME/dlp_sample.csv
 */
function create_job(
    string $callingProjectId,
    string $gcsPath
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Set autoPopulateTimespan to true to scan only new content.
    $timespanConfig = (new TimespanConfig())
        ->setEnableAutoPopulationOfTimespanConfig(true);

    // Specify the GCS file to be inspected.
    $cloudStorageOptions = (new CloudStorageOptions())
        ->setFileSet((new FileSet())
            ->setUrl($gcsPath));
    $storageConfig = (new StorageConfig())
        ->setCloudStorageOptions(($cloudStorageOptions))
        ->setTimespanConfig($timespanConfig);

    // ----- Construct inspection config -----
    $emailAddressInfoType = (new InfoType())
        ->setName('EMAIL_ADDRESS');
    $personNameInfoType = (new InfoType())
        ->setName('PERSON_NAME');
    $locationInfoType = (new InfoType())
        ->setName('LOCATION');
    $phoneNumberInfoType = (new InfoType())
        ->setName('PHONE_NUMBER');
    $infoTypes = [$emailAddressInfoType, $personNameInfoType, $locationInfoType, $phoneNumberInfoType];

    // Whether to include the matching string in the response.
    $includeQuote = true;
    // The minimum likelihood required before returning a match.
    $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

    // The maximum number of findings to report (0 = server maximum).
    $limits = (new FindingLimits())
        ->setMaxFindingsPerRequest(100);

    // Create the Inspect configuration object.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood($minLikelihood)
        ->setLimits($limits)
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote($includeQuote);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Configure the inspection job we want the service to perform.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $createDlpJobRequest = (new CreateDlpJobRequest())
        ->setParent($parent)
        ->setInspectJob($inspectJobConfig);
    $job = $dlp->createDlpJob($createDlpJobRequest);

    // Print results.
    printf($job->getName());
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import google.cloud.dlp


def create_dlp_job(
    project: str,
    bucket: str,
    info_types: list[str],
    job_id: str = None,
    max_findings: int = 100,
    auto_populate_timespan: bool = True,
) -> None:
    """Uses the Data Loss Prevention API to create a DLP job.
    Args:
        project: The project id to use as a parent resource.
        bucket: The name of the GCS bucket to scan. This sample scans all
            files in the bucket.
        info_types: A list of strings representing info types to look for.
            A full list of info type categories can be fetched from the API.
        job_id: The id of the job. If omitted, an id will be randomly generated.
        max_findings: The maximum number of findings to report; 0 = no maximum.
        auto_populate_timespan: Automatically populates time span config start
            and end times in order to scan new content only.
    """

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

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

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries (protos are also accepted).
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary. Keys which are None may
    # optionally be omitted entirely.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a cloud_storage_options dictionary with the bucket's URL.
    url = f"gs://{bucket}/*"
    storage_config = {
        "cloud_storage_options": {"file_set": {"url": url}},
        # Time-based configuration for each storage object.
        "timespan_config": {
            # Auto-populate start and end times in order to scan new objects
            # only.
            "enable_auto_population_of_timespan_config": auto_populate_timespan
        },
    }

    # Construct the job definition.
    job = {"inspect_config": inspect_config, "storage_config": storage_config}

    # Call the API.
    response = dlp.create_dlp_job(
        request={"parent": parent, "inspect_job": job, "job_id": job_id}
    )

    # Print out the result.
    print(f"Job : {response.name} status: {response.state}")

REST

工作在 DLP API 中會以 DlpJobs 資源表示。您可以使用 DlpJob 資源的 projects.dlpJobs.create 方法建立新工作。

您可以在傳送 POST 要求時將以下 JSON 範例傳送至指定的 Sensitive Data Protection REST 端點。這個 JSON 範例示範如何在 Sensitive Data Protection 中建立工作。這項工作是 Datastore 檢查掃描。

如要快速嘗試,可以使用下方內嵌的 API Explorer。請注意,即使在 API Explorer 中建立,成功提出的要求仍將建立工作。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

JSON 輸入:

{
  "inspectJob": {
    "storageConfig": {
      "bigQueryOptions": {
        "tableReference": {
          "projectId": "bigquery-public-data",
          "datasetId": "san_francisco_sfpd_incidents",
          "tableId": "sfpd_incidents"
        }
      },
      "timespanConfig": {
        "startTime": "2020-01-01T00:00:01Z",
        "endTime": "2020-01-31T23:59:59Z",
        "timestampField": {
          "name": "timestamp"
        }
      }
    },
    "inspectConfig": {
      "infoTypes": [
        {
          "name": "PERSON_NAME"
        },
        {
          "name": "STREET_ADDRESS"
        }
      ],
      "excludeInfoTypes": false,
      "includeQuote": true,
      "minLikelihood": "LIKELY"
    },
    "actions": [
      {
        "saveFindings": {
          "outputConfig": {
            "table": {
              "projectId": "[PROJECT-ID]",
              "datasetId": "[DATASET-ID]"
            }
          }
        }
      }
    ]
  }
}

JSON 輸出:

以下輸出內容表示工作已成功建立。

{
  "name": "projects/[PROJECT-ID]/dlpJobs/[JOB-ID]",
  "type": "INSPECT_JOB",
  "state": "PENDING",
  "inspectDetails": {
    "requestedOptions": {
      "snapshotInspectTemplate": {},
      "jobConfig": {
        "storageConfig": {
          "bigQueryOptions": {
            "tableReference": {
              "projectId": "bigquery-public-data",
              "datasetId": "san_francisco_sfpd_incidents",
              "tableId": "sfpd_incidents"
            }
          },
          "timespanConfig": {
            "startTime": "2020-01-01T00:00:01Z",
            "endTime": "2020-01-31T23:59:59Z",
            "timestampField": {
              "name": "timestamp"
            }
          }
        },
        "inspectConfig": {
          "infoTypes": [
            {
              "name": "PERSON_NAME"
            },
            {
              "name": "STREET_ADDRESS"
            }
          ],
          "minLikelihood": "LIKELY",
          "limits": {},
          "includeQuote": true
        },
        "actions": [
          {
            "saveFindings": {
              "outputConfig": {
                "table": {
                  "projectId": "[PROJECT-ID]",
                  "datasetId": "[DATASET-ID]",
                  "tableId": "[TABLE-ID]"
                }
              }
            }
          }
        ]
      }
    },
    "result": {}
  },
  "createTime": "2020-07-10T07:26:33.643Z"
}

建立新的工作觸發條件

如要建立新的 Sensitive Data Protection 工作觸發條件,請按照下列步驟操作:

控制台

在 Google Cloud 控制台的「Sensitive Data Protection」專區中,前往「Create job or job trigger」頁面。

前往「建立工作或工作觸發條件」

「Create job or job trigger」(建立工作或工作觸發條件) 頁面包含下列章節:

選擇輸入資料

名稱

輸入工作觸發條件的名稱。您可以使用英文字母、數字和連字號。 您可以選擇是否為工作觸發條件命名。如果您未輸入名稱,Sensitive Data Protection 會為工作觸發程序指派專屬數字 ID。

位置

從「Storage type」(儲存空間類型) 選單中,選擇用於儲存您要掃描之資料的存放區類型:

  • Cloud Storage:輸入要掃描的值區網址,或從「Location type」(位置類型) 選單中選擇「Include/exclude」(納入/排除),然後按一下「Browse」(瀏覽),前往要掃描的值區或子資料夾。選取「以遞迴方式掃描資料夾」核取方塊,即可掃描指定目錄和所有內含目錄。取消選取該核取方塊可僅掃描指定目錄,而不深入掃描。
  • BigQuery:輸入要掃描的專案、資料集和資料表 ID。
  • Datastore:輸入要掃描的專案、命名空間 (選用) 和種類的 ID。

取樣

如果您擁有非常龐大的資料量,取樣是一種可節省資源的選擇性方法。

在 [Sampling] (取樣方法) 下,您可以選擇掃描所有選取的資料,還是透過掃描特定百分比來取樣資料。取樣的工作方式會視您掃描的儲存空間存放區類型而有所不同:

  • 針對 BigQuery,您可以取樣所有已選取資料列的子集,並對應於您指定要包含在掃描作業內的檔案百分比。
  • 針對 Cloud Storage,如果任何檔案超出「Max byte size to scan per file」(每個待掃描檔案的位元組大小上限) 中指定的大小,Sensitive Data Protection 最多會掃描至該檔案大小上限,然後移至下一個檔案。

如要開啟取樣,請從第一個選單中選擇下列其中一個選項:

  • 從頭開始取樣:Sensitive Data Protection 會從資料的開頭開始部分掃描。針對 BigQuery,此設定會從第一個資料列開始掃描。針對 Cloud Storage,此設定會從每個檔案的開頭開始掃描,並在 Sensitive Data Protection 掃描到任何指定檔案大小上限 (請參閱上述說明) 之後停止掃描。
  • 隨機開始取樣:Sensitive Data Protection 會從資料的隨機位置開始部分掃描。針對 BigQuery,此設定會從隨機資料列開始掃描。針對 Cloud Storage,此設定僅適用於超出任何指定大小上限的檔案。Sensitive Data Protection 掃描檔案的整體大小會低於檔案大小上限,若高於檔案大小上限,則會掃描到該上限為止。

如要執行部分掃描,您也必須選擇想要掃描的資料百分比。使用滑桿可設定百分比。

進階設定

當您針對 Cloud Storage bucket 或 BigQuery 資料表建立工作觸發條件時,可指定進階設定來縮小搜尋範圍。具體而言,您可以設定:

  • 檔案 (僅限 Cloud Storage):要掃描的檔案類型,包括文字、二進位檔和圖片檔。
  • 識別欄位 (僅限 BigQuery):表格中的不重複資料列 ID。
  • 針對 Cloud Storage,如果任何檔案超出「Max byte size to scan per file」(每個待掃描檔案的位元組大小上限) 中指定的大小,Sensitive Data Protection 最多會掃描至該檔案大小上限,然後移至下一個檔案。

如要開啟取樣功能,請選擇要掃描的資料百分比。使用滑桿設定百分比。然後從第一個選單中選擇下列其中一個選項:

  • 從頭開始取樣:Sensitive Data Protection 會從資料的開頭開始部分掃描。針對 BigQuery,此設定會從第一個資料列開始掃描。針對 Cloud Storage,此設定會從每個檔案的開頭開始掃描,並在 Sensitive Data Protection 掃描到任何指定檔案大小上限 (請參閱上述說明) 之後停止掃描。
  • 隨機開始取樣:Sensitive Data Protection 會從資料的隨機位置開始部分掃描。針對 BigQuery,此設定會從隨機資料列開始掃描。針對 Cloud Storage,此設定僅適用於超出任何指定大小上限的檔案。Sensitive Data Protection 掃描檔案的整體大小會低於檔案大小上限,若高於檔案大小上限,則會掃描到該上限為止。

檔案

針對儲存在 Cloud Storage 中的檔案,您可以在「Files」(檔案) 下指定要包含在掃描中的類型。

您可以選擇二進位檔、文字、圖片、Microsoft Word、Microsoft Excel、Microsoft PowerPoint、PDF 和 Apache Avro 檔案。如需 Sensitive Data Protection 可在 Cloud Storage 值區中掃描的副檔名完整清單,請參閱 FileType。選擇「二進位檔」會導致 Sensitive Data Protection 掃描無法辨識的檔案類型。

識別欄位

如果是 BigQuery 中的資料表,您可以在「識別欄位」欄位中,指示 Sensitive Data Protection 在結果中加入資料表主鍵欄的值。這麼做可將發現項目連結回包含這些項目的資料表列。

輸入可唯一識別資料表中每個資料列的資料欄名稱。如有需要,請使用點標記法指定巢狀欄位。您可以視需要新增任意數量的欄位。

您也必須開啟「儲存至 BigQuery」動作,才能將發現項目匯出至 BigQuery。將發現項目匯出至 BigQuery 時,每個發現項目都會包含識別欄位的相應值。詳情請參閱 identifyingFields 的說明。

設定偵測作業

「Configure detection」(設定偵測作業) 區段可讓您指定想要掃描的機密資料類型。你可以選擇是否填寫這個部分。如果略過這個部分,Sensitive Data Protection 會掃描資料,找出預設的一組 infoTypes

範本

您可以選擇使用 Sensitive Data Protection 範本,重複使用先前已指定的設定資訊。

如果您已建立要使用的範本,請按一下「範本名稱」欄位,查看現有檢查範本清單。選擇或輸入要使用的範本名稱。

如要進一步瞭解如何建立範本,請參閱建立機密資料保護檢查範本一文。

InfoType

InfoType 偵測工具可尋找特定類型的機密資料。舉例來說,Sensitive Data Protection US_SOCIAL_SECURITY_NUMBER 內建的 infoType 偵測工具可尋找美國社會安全號碼。除了內建的 infoType 偵測工具,您也可以建立自己的自訂 infoType 偵測工具

在「InfoType」底下,根據您要掃描的資料類型,選擇對應的 infoType 偵測工具。您也可以將此欄位保留空白,以掃描所有預設 infoType。InfoType 偵測工具參考資料中提供每個偵測工具的詳細資訊。

您也可以在「自訂 infoType」專區新增自訂 infoType 偵測工具,並在「檢查規則集」專區自訂內建和自訂 infoType 偵測工具。

自訂 InfoType
檢查規則集
可信度門檻

每當敏感資料保護偵測到可能符合敏感資料的項目,就會在「非常不可能」到「非常可能」的範圍內,為該項目指派「可能性」值。在此設定可能性值時,您是在指示 Sensitive Data Protection 只比對符合該可能性值或更高的資料。

預設值「Possible」(或許可能) 足以供大多數情況使用。如果您經常得到過於寬泛的相符項目,請將滑桿上移。如果您得到的相符項目太少,請將滑桿下移。

完成後,按一下 [Continue] (繼續)

新增動作

在「Add actions」(新增動作) 步驟中,選取想讓 Sensitive Data Protection 在工作完成之後執行的一或多個動作。

您可以設定下列動作:

  • 儲存至 BigQuery:將 Sensitive Data Protection 工作結果儲存至 BigQuery 資料表。您必須先確認工作已經完成,才能查看或分析結果。

    每次執行掃描時,Sensitive Data Protection 都會將掃描結果儲存到您指定的 BigQuery 資料表。匯出的發現項目包含每個發現項目位置與相符可能性的詳細資料。如要讓每項發現都包含與 infoType 偵測工具相符的字串,請啟用「Include quote」(包含引號) 選項。

    如果您未指定表格 ID,BigQuery 會在首次執行掃描作業時,為新表格指派預設名稱。如果您指定現有的資料表,Sensitive Data Protection 會將掃描結果附加至該資料表。

    如未將發現項目儲存至 BigQuery,掃描結果只會包含與發現項目的數量和 infoType 相關的統計資料。

    將資料寫入 BigQuery 資料表時,費用與配額用量會計入目的地資料表所屬專案。

  • 發布至 Pub/Sub:將含有 Sensitive Data Protection 工作名稱的通知發布至 Pub/Sub 管道。您可以指定一或多個主題,將通知訊息傳送至這些主題。請確認執行掃描作業的 Sensitive Data Protection 服務帳戶具有主題的發布存取權。

  • 發布至 Security Command Center:將工作結果摘要發布至 Security Command Center。詳情請參閱「將 Sensitive Data Protection 掃描結果傳送至 Security Command Center」。

  • 發布至 Dataplex (已淘汰):將檢查工作結果傳送至 Dataplex Universal Catalog,這是 Google Cloud的中繼資料管理服務。

  • 透過電子郵件通知:作業完成時傳送電子郵件。這封電子郵件會傳送給身分與存取權管理專案擁有者和技術重要聯絡人

  • 發布至 Cloud Monitoring:將檢查結果傳送至 Google Cloud Observability 中的 Cloud Monitoring。

  • 建立去識別化副本:將檢查資料中的所有發現項目去識別化,然後將去識別化內容寫入新檔案。然後,您可以在業務程序中使用去識別化副本,取代含有私密資訊的資料。詳情請參閱「使用 Google Cloud 控制台中的 Sensitive Data Protection,建立 Cloud Storage 資料的去識別化副本」。

詳情請參閱「動作」。

選取動作之後,按一下 [Continue] (繼續)

排程

在「Schedule」(排程) 區段中,您可以執行兩項操作:

  • 指定時距:此選項可將檔案或資料列限制為按日期掃描。 按一下「開始時間」,指定要納入的最早檔案時間戳記。 將此值保留空白可指定所有檔案。按一下「結束時間」,指定要納入的最晚檔案時間戳記。將此值保留空白可不指定時間戳記上限。
  • 建立觸發條件來定期執行工作:此選項可將工作轉換為定期執行的工作觸發條件。如果您未指定排程,則實際上會建立馬上開始執行一次的工作。如要建立定期執行的工作觸發條件,您必須設定此選項。

    預設值也是最小值:24 小時。最大值為 60 天。

    如要讓機密資料保護功能只掃描新檔案或資料列,請選取「將掃描限制為僅新內容」。如為 BigQuery 檢查,則只會掃描存在時間滿三小時的資料列。請參閱與這項作業相關的已知問題

查看

「Review」(查看) 區段包含您剛指定之工作設定的 JSON 格式摘要。

按一下「建立」即可建立工作觸發條件 (若您指定了排程)。隨即會顯示工作觸發條件的資訊頁面,其中包含狀態及其他資訊。如果目前正在執行工作,您可以按一下「取消」按鈕來停止工作,也可以按一下「刪除」,刪除工作觸發條件。

如要返回「Sensitive Data Protection」主頁面,請在 Google Cloud 控制台中按一下「返回」箭頭。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using System;
using System.Collections.Generic;
using static Google.Cloud.Dlp.V2.CloudStorageOptions.Types;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;
using static Google.Cloud.Dlp.V2.JobTrigger.Types;
using static Google.Cloud.Dlp.V2.StorageConfig.Types;

public class TriggersCreate
{
    public static JobTrigger Create(
        string projectId,
        string bucketName,
        Likelihood minLikelihood,
        int maxFindings,
        bool autoPopulateTimespan,
        int scanPeriod,
        IEnumerable<InfoType> infoTypes,
        string triggerId,
        string displayName,
        string description)
    {
        var dlp = DlpServiceClient.Create();

        var jobConfig = new InspectJobConfig
        {
            InspectConfig = new InspectConfig
            {
                MinLikelihood = minLikelihood,
                Limits = new FindingLimits
                {
                    MaxFindingsPerRequest = maxFindings
                },
                InfoTypes = { infoTypes }
            },
            StorageConfig = new StorageConfig
            {
                CloudStorageOptions = new CloudStorageOptions
                {
                    FileSet = new FileSet
                    {
                        Url = $"gs://{bucketName}/*"
                    }
                },
                TimespanConfig = new TimespanConfig
                {
                    EnableAutoPopulationOfTimespanConfig = autoPopulateTimespan
                }
            }
        };

        var jobTrigger = new JobTrigger
        {
            Triggers =
            {
                new Trigger
                {
                    Schedule = new Schedule
                    {
                        RecurrencePeriodDuration = new Google.Protobuf.WellKnownTypes.Duration
                        {
                            Seconds = scanPeriod * 60 * 60 * 24
                        }
                    }
                }
            },
            InspectJob = jobConfig,
            Status = Status.Healthy,
            DisplayName = displayName,
            Description = description
        };

        var response = dlp.CreateJobTrigger(
            new CreateJobTriggerRequest
            {
                Parent = new LocationName(projectId, "global").ToString(),
                JobTrigger = jobTrigger,
                TriggerId = triggerId
            });

        Console.WriteLine($"Successfully created trigger {response.Name}");
        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"github.com/golang/protobuf/ptypes/duration"
)

// createTrigger creates a trigger with the given configuration.
func createTrigger(w io.Writer, projectID string, triggerID, displayName, description, bucketName string, infoTypeNames []string) error {
	// projectID := "my-project-id"
	// triggerID := "my-trigger"
	// displayName := "My Trigger"
	// description := "My trigger description"
	// bucketName := "my-bucket"
	// infoTypeNames := []string{"US_SOCIAL_SECURITY_NUMBER"}

	ctx := context.Background()

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

	// Convert the info type strings to a list of InfoTypes.
	var infoTypes []*dlppb.InfoType
	for _, it := range infoTypeNames {
		infoTypes = append(infoTypes, &dlppb.InfoType{Name: it})
	}

	// Create a configured request.
	req := &dlppb.CreateJobTriggerRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/global", projectID),
		TriggerId: triggerID,
		JobTrigger: &dlppb.JobTrigger{
			DisplayName: displayName,
			Description: description,
			Status:      dlppb.JobTrigger_HEALTHY,
			// Triggers control when the job will start.
			Triggers: []*dlppb.JobTrigger_Trigger{
				{
					Trigger: &dlppb.JobTrigger_Trigger_Schedule{
						Schedule: &dlppb.Schedule{
							Option: &dlppb.Schedule_RecurrencePeriodDuration{
								RecurrencePeriodDuration: &duration.Duration{
									Seconds: 10 * 60 * 60 * 24, // 10 days in seconds.
								},
							},
						},
					},
				},
			},
			// Job configures the job to run when the trigger runs.
			Job: &dlppb.JobTrigger_InspectJob{
				InspectJob: &dlppb.InspectJobConfig{
					InspectConfig: &dlppb.InspectConfig{
						InfoTypes:     infoTypes,
						MinLikelihood: dlppb.Likelihood_POSSIBLE,
						Limits: &dlppb.InspectConfig_FindingLimits{
							MaxFindingsPerRequest: 10,
						},
					},
					StorageConfig: &dlppb.StorageConfig{
						Type: &dlppb.StorageConfig_CloudStorageOptions{
							CloudStorageOptions: &dlppb.CloudStorageOptions{
								FileSet: &dlppb.CloudStorageOptions_FileSet{
									Url: "gs://" + bucketName + "/*",
								},
							},
						},
						// Time-based configuration for each storage object. See more at
						// https://cloud.google.com/dlp/docs/reference/rest/v2/InspectJobConfig#TimespanConfig
						TimespanConfig: &dlppb.StorageConfig_TimespanConfig{
							// Auto-populate start and end times in order to scan new objects only.
							EnableAutoPopulationOfTimespanConfig: true,
						},
					},
				},
			},
		},
	}

	// Send the request.
	resp, err := client.CreateJobTrigger(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateJobTrigger: %w", err)
	}
	fmt.Fprintf(w, "Successfully created trigger: %v", resp.GetName())
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CloudStorageOptions;
import com.google.privacy.dlp.v2.CreateJobTriggerRequest;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.JobTrigger;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.Schedule;
import com.google.privacy.dlp.v2.StorageConfig;
import com.google.privacy.dlp.v2.StorageConfig.TimespanConfig;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TriggersCreate {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String gcsPath = "gs://" + "your-bucket-name" + "path/to/file.txt";
    createTrigger(projectId, gcsPath);
  }

  public static void createTrigger(String projectId, String gcsPath) 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()) {

      // Set autoPopulateTimespan to true to scan only new content
      boolean autoPopulateTimespan = true;
      TimespanConfig timespanConfig =
          TimespanConfig.newBuilder()
              .setEnableAutoPopulationOfTimespanConfig(autoPopulateTimespan)
              .build();

      // Specify the GCS file to be inspected.
      CloudStorageOptions cloudStorageOptions =
          CloudStorageOptions.newBuilder()
              .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
              .build();
      StorageConfig storageConfig =
          StorageConfig.newBuilder()
              .setCloudStorageOptions(cloudStorageOptions)
              .setTimespanConfig(timespanConfig)
              .build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      List<InfoType> infoTypes =
          Stream.of("PHONE_NUMBER", "EMAIL_ADDRESS", "CREDIT_CARD_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .build();

      // Set scanPeriod to the number of days between scans (minimum: 1 day)
      int scanPeriod = 1;

      // Optionally set a display name of max 100 chars and a description of max 250 chars
      String displayName = "Daily Scan";
      String description = "A daily inspection for personally identifiable information.";

      // Schedule scan of GCS bucket every scanPeriod number of days (minimum = 1 day)
      Duration duration = Duration.newBuilder().setSeconds(scanPeriod * 24 * 3600).build();
      Schedule schedule = Schedule.newBuilder().setRecurrencePeriodDuration(duration).build();
      JobTrigger.Trigger trigger = JobTrigger.Trigger.newBuilder().setSchedule(schedule).build();
      JobTrigger jobTrigger =
          JobTrigger.newBuilder()
              .setInspectJob(inspectJobConfig)
              .setDisplayName(displayName)
              .setDescription(description)
              .setStatus(JobTrigger.Status.HEALTHY)
              .addTriggers(trigger)
              .build();

      // Create scan request to be sent by client
      CreateJobTriggerRequest createJobTriggerRequest =
          CreateJobTriggerRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setJobTrigger(jobTrigger)
              .build();

      // Send the scan request and process the response
      JobTrigger createdJobTrigger = dlpServiceClient.createJobTrigger(createJobTriggerRequest);

      System.out.println("Created Trigger: " + createdJobTrigger.getName());
      System.out.println("Display Name: " + createdJobTrigger.getDisplayName());
      System.out.println("Description: " + createdJobTrigger.getDescription());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// (Optional) The name of the trigger to be created.
// const triggerId = 'my-trigger';

// (Optional) A display name for the trigger to be created
// const displayName = 'My Trigger';

// (Optional) A description for the trigger to be created
// const description = "This is a sample trigger.";

// The name of the bucket to scan.
// const bucketName = 'YOUR-BUCKET';

// Limit scan to new content only.
// const autoPopulateTimespan = true;

// How often to wait between scans, in days (minimum = 1 day)
// const scanPeriod = 1;

// The infoTypes of information to match
// const infoTypes = [{ name: 'PHONE_NUMBER' }, { name: 'EMAIL_ADDRESS' }, { name: 'CREDIT_CARD_NUMBER' }];

// The minimum likelihood required before returning a match
// const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

// The maximum number of findings to report per request (0 = server maximum)
// const maxFindings = 0;

async function createTrigger() {
  // Get reference to the bucket to be inspected
  const storageItem = {
    cloudStorageOptions: {
      fileSet: {url: `gs://${bucketName}/*`},
    },
    timeSpanConfig: {
      enableAutoPopulationOfTimespanConfig: autoPopulateTimespan,
    },
  };

  // Construct job to be triggered
  const job = {
    inspectConfig: {
      infoTypes: infoTypes,
      minLikelihood: minLikelihood,
      limits: {
        maxFindingsPerRequest: maxFindings,
      },
    },
    storageConfig: storageItem,
  };

  // Construct trigger creation request
  const request = {
    parent: `projects/${projectId}/locations/global`,
    jobTrigger: {
      inspectJob: job,
      displayName: displayName,
      description: description,
      triggers: [
        {
          schedule: {
            recurrencePeriodDuration: {
              seconds: scanPeriod * 60 * 60 * 24, // Trigger the scan daily
            },
          },
        },
      ],
      status: 'HEALTHY',
    },
    triggerId: triggerId,
  };

  // Run trigger creation request
  const [trigger] = await dlp.createJobTrigger(request);
  console.log(`Successfully created trigger ${trigger.name}.`);
}

createTrigger();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
use Google\Cloud\Dlp\V2\CreateJobTriggerRequest;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\JobTrigger;
use Google\Cloud\Dlp\V2\JobTrigger\Status;
use Google\Cloud\Dlp\V2\JobTrigger\Trigger;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Schedule;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\StorageConfig\TimespanConfig;
use Google\Protobuf\Duration;

/**
 * Create a Data Loss Prevention API job trigger.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $bucketName           The name of the bucket to scan
 * @param string $triggerId            (Optional) The name of the trigger to be created
 * @param string $displayName          (Optional) The human-readable name to give the trigger
 * @param string $description          (Optional) A description for the trigger to be created
 * @param int    $scanPeriod           (Optional) How often to wait between scans, in days (minimum = 1 day)
 * @param bool   $autoPopulateTimespan (Optional) Automatically limit scan to new content only
 * @param int    $maxFindings          (Optional) The maximum number of findings to report per request (0 = server maximum)
 */
function create_trigger(
    string $callingProjectId,
    string $bucketName,
    string $triggerId,
    string $displayName,
    string $description,
    int $scanPeriod,
    bool $autoPopulateTimespan,
    int $maxFindings
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // ----- Construct job config -----
    // The infoTypes of information to match
    $personNameInfoType = (new InfoType())
        ->setName('PERSON_NAME');
    $phoneNumberInfoType = (new InfoType())
        ->setName('PHONE_NUMBER');
    $infoTypes = [$personNameInfoType, $phoneNumberInfoType];

    // The minimum likelihood required before returning a match
    $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

    // Specify finding limits
    $limits = (new FindingLimits())
        ->setMaxFindingsPerRequest($maxFindings);

    // Create the inspectConfig object
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood($minLikelihood)
        ->setLimits($limits)
        ->setInfoTypes($infoTypes);

    // Create triggers
    $duration = (new Duration())
        ->setSeconds($scanPeriod * 60 * 60 * 24);

    $schedule = (new Schedule())
        ->setRecurrencePeriodDuration($duration);

    $triggerObject = (new Trigger())
        ->setSchedule($schedule);

    // Create the storageConfig object
    $fileSet = (new FileSet())
        ->setUrl('gs://' . $bucketName . '/*');

    $storageOptions = (new CloudStorageOptions())
        ->setFileSet($fileSet);

    // Auto-populate start and end times in order to scan new objects only.
    $timespanConfig = (new TimespanConfig())
        ->setEnableAutoPopulationOfTimespanConfig($autoPopulateTimespan);

    $storageConfig = (new StorageConfig())
        ->setCloudStorageOptions($storageOptions)
        ->setTimespanConfig($timespanConfig);

    // Construct the jobConfig object
    $jobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig);

    // ----- Construct trigger object -----
    $jobTriggerObject = (new JobTrigger())
        ->setTriggers([$triggerObject])
        ->setInspectJob($jobConfig)
        ->setStatus(Status::HEALTHY)
        ->setDisplayName($displayName)
        ->setDescription($description);

    // Run trigger creation request
    $parent = $dlp->locationName($callingProjectId, 'global');
    $createJobTriggerRequest = (new CreateJobTriggerRequest())
        ->setParent($parent)
        ->setJobTrigger($jobTriggerObject)
        ->setTriggerId($triggerId);
    $trigger = $dlp->createJobTrigger($createJobTriggerRequest);

    // Print results
    printf('Successfully created trigger %s' . PHP_EOL, $trigger->getName());
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from typing import Optional

import google.cloud.dlp


def create_trigger(
    project: str,
    bucket: str,
    scan_period_days: int,
    info_types: List[str],
    trigger_id: Optional[str] = None,
    display_name: Optional[str] = None,
    description: Optional[str] = None,
    min_likelihood: Optional[int] = None,
    max_findings: Optional[int] = None,
    auto_populate_timespan: Optional[bool] = False,
) -> None:
    """Creates a scheduled Data Loss Prevention API inspect_content trigger.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        bucket: The name of the GCS bucket to scan. This sample scans all
            files in the bucket using a wildcard.
        scan_period_days: How often to repeat the scan, in days.
            The minimum is 1 day.
        info_types: A list of strings representing info types to look for.
            A full list of info type categories can be fetched from the API.
        trigger_id: The id of the trigger. If omitted, an id will be randomly
            generated.
        display_name: The optional display name of the trigger.
        description: The optional description of the trigger.
        min_likelihood: A string representing the minimum likelihood threshold
            that constitutes a match. One of: 'LIKELIHOOD_UNSPECIFIED',
            'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY'.
        max_findings: The maximum number of findings to report; 0 = no maximum.
        auto_populate_timespan: Automatically populates time span config start
            and end times in order to scan new content only.
    Returns:
        None; the response from the API is printed to the terminal.
    """

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

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries (protos are also accepted).
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary. Keys which are None may
    # optionally be omitted entirely.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": min_likelihood,
        "limits": {"max_findings_per_request": max_findings},
    }

    # Construct a cloud_storage_options dictionary with the bucket's URL.
    url = f"gs://{bucket}/*"
    storage_config = {
        "cloud_storage_options": {"file_set": {"url": url}},
        # Time-based configuration for each storage object.
        "timespan_config": {
            # Auto-populate start and end times in order to scan new objects
            # only.
            "enable_auto_population_of_timespan_config": auto_populate_timespan
        },
    }

    # Construct the job definition.
    job = {"inspect_config": inspect_config, "storage_config": storage_config}

    # Construct the schedule definition:
    schedule = {
        "recurrence_period_duration": {"seconds": scan_period_days * 60 * 60 * 24}
    }

    # Construct the trigger definition.
    job_trigger = {
        "inspect_job": job,
        "display_name": display_name,
        "description": description,
        "triggers": [{"schedule": schedule}],
        "status": google.cloud.dlp_v2.JobTrigger.Status.HEALTHY,
    }

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

    # Call the API.
    response = dlp.create_job_trigger(
        request={"parent": parent, "job_trigger": job_trigger, "trigger_id": trigger_id}
    )

    print(f"Successfully created trigger {response.name}")

REST

工作觸發條件在 DLP API 中會以 JobTrigger 資源表示。您可以使用 JobTrigger 資源的 projects.jobTriggers.create 方法建立新的工作觸發條件。

您可以在傳送 POST 要求時將以下 JSON 範例傳送至指定的 Sensitive Data Protection REST 端點。這個 JSON 範例示範如何在敏感資料保護中建立工作觸發條件。此觸發條件啟動的工作是 Datastore 檢查掃描。已建立的工作觸發條件會每隔 86,400 秒 (或 24 小時) 執行一次。

如要快速嘗試,可以使用下方內嵌的 API Explorer。請注意,即使在 API Explorer 中建立,成功提出的要求仍將建立新排定的工作觸發條件。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門導覽課程

JSON 輸入:

{
  "jobTrigger":{
    "displayName":"JobTrigger1",
    "description":"Starts an inspection of a Datastore kind",
    "triggers":[
      {
        "schedule":{
          "recurrencePeriodDuration":"86400s"
        }
      }
    ],
    "status":"HEALTHY",
    "inspectJob":{
      "storageConfig":{
        "datastoreOptions":{
          "kind":{
            "name":"Example-Kind"
          },
          "partitionId":{
            "projectId":"[PROJECT_ID]",
            "namespaceId":"[NAMESPACE_ID]"
          }
        }
      },
      "inspectConfig":{
        "infoTypes":[
          {
            "name":"PHONE_NUMBER"
          }
        ],
        "excludeInfoTypes":false,
        "includeQuote":true,
        "minLikelihood":"LIKELY"
      },
      "actions":[
        {
          "saveFindings":{
            "outputConfig":{
              "table":{
                "projectId":"[PROJECT_ID]",
                "datasetId":"[BIGQUERY_DATASET_NAME]",
                "tableId":"[BIGQUERY_TABLE_NAME]"
              }
            }
          }
        }
      ]
    }
  }
}

JSON 輸出:

以下輸出表示工作觸發條件已成功建立。

{
  "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
  "displayName":"JobTrigger1",
  "description":"Starts an inspection of a Datastore kind",
  "inspectJob":{
    "storageConfig":{
      "datastoreOptions":{
        "partitionId":{
          "projectId":"[PROJECT_ID]",
          "namespaceId":"[NAMESPACE_ID]"
        },
        "kind":{
          "name":"Example-Kind"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "minLikelihood":"LIKELY",
      "limits":{

      },
      "includeQuote":true
    },
    "actions":[
      {
        "saveFindings":{
          "outputConfig":{
            "table":{
              "projectId":"[PROJECT_ID]",
              "datasetId":"[BIGQUERY_DATASET_NAME]",
              "tableId":"[BIGQUERY_TABLE_NAME]"
            }
          }
        }
      }
    ]
  },
  "triggers":[
    {
      "schedule":{
        "recurrencePeriodDuration":"86400s"
      }
    }
  ],
  "createTime":"2018-11-30T01:52:41.171857Z",
  "updateTime":"2018-11-30T01:52:41.171857Z",
  "status":"HEALTHY"
}

列出所有工作

如要列出目前專案的所有工作:

控制台

  1. 在 Google Cloud 控制台中,前往「Sensitive Data Protection」頁面。

    前往 Sensitive Data Protection

  2. 按一下「檢查」分頁標籤,然後按一下「檢查工作」子分頁標籤。

主控台會顯示目前專案的所有工作清單,包括工作 ID、狀態、建立時間和結束時間。如要進一步瞭解任何工作 (包括結果摘要),請按一下其 ID。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

public class JobsList
{
    public static PagedEnumerable<ListDlpJobsResponse, DlpJob> ListDlpJobs(string projectId, string filter, DlpJobType jobType)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.ListDlpJobs(new ListDlpJobsRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            Filter = filter,
            Type = jobType
        });

        // Uncomment to print jobs
        // foreach (var job in response)
        // {
        //     Console.WriteLine($"Job: {job.Name} status: {job.State}");
        // }

        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"google.golang.org/api/iterator"
)

// listJobs lists jobs matching the given optional filter and optional jobType.
func listJobs(w io.Writer, projectID, filter, jobType string) error {
	// projectID := "my-project-id"
	// filter := "`state` = FINISHED"
	// jobType := "RISK_ANALYSIS_JOB"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	// Create a configured request.
	req := &dlppb.ListDlpJobsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Filter: filter,
		Type:   dlppb.DlpJobType(dlppb.DlpJobType_value[jobType]),
	}
	// Send the request and iterate over the results.
	it := client.ListDlpJobs(ctx, req)
	for {
		j, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %w", err)
		}
		fmt.Fprintf(w, "Job %v status: %v\n", j.GetName(), j.GetState())
	}
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.DlpJobType;
import com.google.privacy.dlp.v2.ListDlpJobsRequest;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;

public class JobsList {

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

  // Lists DLP jobs
  public static void listJobs(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()) {

      // Construct the request to be sent by the client.
      // For more info on filters and job types,
      // see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
      ListDlpJobsRequest listDlpJobsRequest =
          ListDlpJobsRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setFilter("state=DONE")
              .setType(DlpJobType.valueOf("INSPECT_JOB"))
              .build();

      // Send the request to list jobs and process the response
      DlpServiceClient.ListDlpJobsPagedResponse response =
          dlpServiceClient.listDlpJobs(listDlpJobsRequest);

      System.out.println("DLP jobs found:");
      for (DlpJob dlpJob : response.getPage().getValues()) {
        System.out.println(dlpJob.getName() + " -- " + dlpJob.getState());
      }
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The filter expression to use
// For more information and filter syntax, see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
// const filter = `state=DONE`;

// The type of job to list (either 'INSPECT_JOB' or 'RISK_ANALYSIS_JOB')
// const jobType = 'INSPECT_JOB';
async function listJobs() {
  // Construct request for listing DLP scan jobs
  const request = {
    parent: `projects/${projectId}/locations/global`,
    filter: filter,
    type: jobType,
  };

  // Run job-listing request
  const [jobs] = await dlp.listDlpJobs(request);
  jobs.forEach(job => {
    console.log(`Job ${job.name} status: ${job.state}`);
  });
}

listJobs();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\DlpJob\JobState;
use Google\Cloud\Dlp\V2\DlpJobType;
use Google\Cloud\Dlp\V2\ListDlpJobsRequest;

/**
 * List Data Loss Prevention API jobs corresponding to a given filter.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 * @param string $filter            The filter expression to use
 */
function list_jobs(string $callingProjectId, string $filter): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // The type of job to list (either 'INSPECT_JOB' or 'REDACT_JOB')
    $jobType = DlpJobType::INSPECT_JOB;

    // Run job-listing request
    // For more information and filter syntax,
    // @see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
    $parent = "projects/$callingProjectId/locations/global";
    $listDlpJobsRequest = (new ListDlpJobsRequest())
        ->setParent($parent)
        ->setFilter($filter)
        ->setType($jobType);
    $response = $dlp->listDlpJobs($listDlpJobsRequest);

    // Print job list
    $jobs = $response->iterateAllElements();
    foreach ($jobs as $job) {
        printf('Job %s status: %s' . PHP_EOL, $job->getName(), $job->getState());
        $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();

        if ($job->getState() == JobState::DONE) {
            if (count($infoTypeStats) > 0) {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of type %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            } else {
                print('  No findings.' . PHP_EOL);
            }
        }
    }
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


from typing import Optional

import google.cloud.dlp


def list_dlp_jobs(
    project: str, filter_string: Optional[str] = None, job_type: Optional[str] = None
) -> None:
    """Uses the Data Loss Prevention API to lists DLP jobs that match the
        specified filter in the request.
    Args:
        project: The project id to use as a parent resource.
        filter: (Optional) Allows filtering.
            Supported syntax:
            * Filter expressions are made up of one or more restrictions.
            * Restrictions can be combined by 'AND' or 'OR' logical operators.
            A sequence of restrictions implicitly uses 'AND'.
            * A restriction has the form of '<field> <operator> <value>'.
            * Supported fields/values for inspect jobs:
                - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED
                - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY
                - `trigger_name` - The resource name of the trigger that
                                   created job.
            * Supported fields for risk analysis jobs:
                - `state` - RUNNING|CANCELED|FINISHED|FAILED
            * The operator must be '=' or '!='.
            Examples:
            * inspected_storage = cloud_storage AND state = done
            * inspected_storage = cloud_storage OR inspected_storage = bigquery
            * inspected_storage = cloud_storage AND
                                  (state = done OR state = canceled)
        type: (Optional) The type of job. Defaults to 'INSPECT'.
            Choices:
            DLP_JOB_TYPE_UNSPECIFIED
            INSPECT_JOB: The job inspected content for sensitive data.
            RISK_ANALYSIS_JOB: The job executed a Risk Analysis computation.

    Returns:
        None; the response from the API is printed to the terminal.
    """

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

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

    # Job type dictionary
    job_type_to_int = {
        "DLP_JOB_TYPE_UNSPECIFIED": google.cloud.dlp.DlpJobType.DLP_JOB_TYPE_UNSPECIFIED,
        "INSPECT_JOB": google.cloud.dlp.DlpJobType.INSPECT_JOB,
        "RISK_ANALYSIS_JOB": google.cloud.dlp.DlpJobType.RISK_ANALYSIS_JOB,
    }
    # If job type is specified, convert job type to number through enums.
    if job_type:
        job_type = job_type_to_int[job_type]

    # Call the API to get a list of jobs.
    response = dlp.list_dlp_jobs(
        request={"parent": parent, "filter": filter_string, "type_": job_type}
    )

    # Iterate over results.
    for job in response:
        print(f"Job: {job.name}; status: {job.state.name}")

REST

DlpJob 資源具有 projects.dlpJobs.list 方法,可用來列出所有工作。

如要列出目前專案中定義的所有工作,請將 GET 要求傳送至 dlpJobs 端點,如下所示:

網址:

GET https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/dlpJobs?key={YOUR_API_KEY}

下列 JSON 輸出內容列出其中一項傳回的工作。請注意,工作結構會與 DlpJob 資源的結構完全相同。

JSON 輸出:

{
  "jobs":[
    {
      "name":"projects/[PROJECT-ID]/dlpJobs/i-5270277269264714623",
      "type":"INSPECT_JOB",
      "state":"DONE",
      "inspectDetails":{
        "requestedOptions":{
          "snapshotInspectTemplate":{
          },
          "jobConfig":{
            "storageConfig":{
              "cloudStorageOptions":{
                "fileSet":{
                  "url":"[CLOUD-STORAGE-URL]"
                },
                "fileTypes":[
                  "FILE_TYPE_UNSPECIFIED"
                ],
                "filesLimitPercent":100
              },
              "timespanConfig":{
                "startTime":"2019-09-08T22:43:16.623Z",
                "enableAutoPopulationOfTimespanConfig":true
              }
            },
            "inspectConfig":{
              "infoTypes":[
                {
                  "name":"US_SOCIAL_SECURITY_NUMBER"
                },
                {
                  "name":"CANADA_SOCIAL_INSURANCE_NUMBER"
                }
              ],
              "minLikelihood":"LIKELY",
              "limits":{
              },
              "includeQuote":true
            },
            "actions":[
              {
                "saveFindings":{
                  "outputConfig":{
                    "table":{
                      "projectId":"[PROJECT-ID]",
                      "datasetId":"[DATASET-ID]",
                      "tableId":"[TABLE-ID]"
                    }
                  }
                }
              }
            ]
          }
        },
        "result":{
          ...
        }
      },
      "createTime":"2019-09-09T22:43:16.918Z",
      "startTime":"2019-09-09T22:43:16.918Z",
      "endTime":"2019-09-09T22:43:53.091Z",
      "jobTriggerName":"projects/[PROJECT-ID]/jobTriggers/sample-trigger2"
    },
    ...

如要快速嘗試,可以使用下方內嵌的 API Explorer。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

列出所有工作觸發條件

如要列出目前專案的所有工作觸發條件:

控制台

在 Google Cloud 控制台中,前往「Sensitive Data Protection」頁面。

前往 Sensitive Data Protection

在「檢查」分頁的「工作觸發條件」子分頁中,主控台會顯示目前專案所有工作觸發條件的清單。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

// 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: %w", 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: %w", err)
		}
		fmt.Fprintf(w, "Trigger %v\n", t.GetName())
		c, err := ptypes.Timestamp(t.GetCreateTime())
		if err != nil {
			return fmt.Errorf("CreateTime Timestamp: %w", 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: %w", 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

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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());
      }
      ;
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project'

async function listTriggers() {
  // Construct trigger listing request
  const request = {
    parent: `projects/${projectId}/locations/global`,
  };

  // Helper function to pretty-print dates
  const formatDate = date => {
    const msSinceEpoch = parseInt(date.seconds, 10) * 1000;
    return new Date(msSinceEpoch).toLocaleString('en-US');
  };

  // Run trigger listing request
  const [triggers] = await dlp.listJobTriggers(request);
  triggers.forEach(trigger => {
    // Log trigger details
    console.log(`Trigger ${trigger.name}:`);
    console.log(`  Created: ${formatDate(trigger.createTime)}`);
    console.log(`  Updated: ${formatDate(trigger.updateTime)}`);
    if (trigger.displayName) {
      console.log(`  Display Name: ${trigger.displayName}`);
    }
    if (trigger.description) {
      console.log(`  Description: ${trigger.description}`);
    }
    console.log(`  Status: ${trigger.status}`);
    console.log(`  Error count: ${trigger.errors.length}`);
  });
}

listTriggers();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\ListJobTriggersRequest;

/**
 * List Data Loss Prevention API job triggers.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 */
function list_triggers(string $callingProjectId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

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

    // Run request
    $listJobTriggersRequest = (new ListJobTriggersRequest())
        ->setParent($parent);
    $response = $dlp->listJobTriggers($listJobTriggersRequest);

    // 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

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import google.cloud.dlp


def list_triggers(project: str) -> None:
    """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.
    """

    # 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(f"Trigger {trigger.name}:")
        print(f"  Created: {trigger.create_time}")
        print(f"  Updated: {trigger.update_time}")
        if trigger.display_name:
            print(f"  Display Name: {trigger.display_name}")
        if trigger.description:
            print(f"  Description: {trigger.description}")
        print(f"  Status: {trigger.status}")
        print(f"  Error count: {len(trigger.errors)}")

REST

JobTrigger 資源具有 projects.jobTriggers.list 方法,可用來列出所有工作觸發條件。

如要列出目前專案中定義的所有工作觸發條件,請將 GET 要求傳送至 jobTriggers 端點,如下所示:

網址:

GET https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/jobTriggers?key={YOUR_API_KEY}

下列 JSON 輸出會列出在上一節中建立的工作觸發條件。請注意,工作觸發條件結構會與 JobTrigger 資源的結構完全相同。

JSON 輸出:

{
  "jobTriggers":[
    {
      "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
      "displayName":"JobTrigger1",
      "description":"Starts an inspection of a Datastore kind",
      "inspectJob":{
        "storageConfig":{
          "datastoreOptions":{
            "partitionId":{
              "projectId":"[PROJECT_ID]",
              "namespaceId":"[NAMESPACE_ID]"
            },
            "kind":{
              "name":"Example-Kind"
            }
          }
        },
        "inspectConfig":{
          "infoTypes":[
            {
              "name":"PHONE_NUMBER"
            }
          ],
          "minLikelihood":"LIKELY",
          "limits":{

          },
          "includeQuote":true
        },
        "actions":[
          {
            "saveFindings":{
              "outputConfig":{
                "table":{
                  "projectId":"[PROJECT_ID]",
                  "datasetId":"[BIGQUERY_DATASET_NAME]",
                  "tableId":"[BIGQUERY_TABLE_NAME]"
                }
              }
            }
          }
        ]
      },
      "triggers":[
        {
          "schedule":{
            "recurrencePeriodDuration":"86400s"
          }
        }
      ],
      "createTime":"2018-11-30T01:52:41.171857Z",
      "updateTime":"2018-11-30T01:52:41.171857Z",
      "status":"HEALTHY"
    },

    ...

],
  "nextPageToken":"KkwKCQjivJ2UpPreAgo_Kj1wcm9qZWN0cy92ZWx2ZXR5LXN0dWR5LTE5NjEwMS9qb2JUcmlnZ2Vycy8xNTA5NzEyOTczMDI0MDc1NzY0"
}

如要快速嘗試,可以使用下方內嵌的 API Explorer。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

刪除工作

如要從專案中刪除工作 (包括結果),請按照下列步驟操作:這項作業不會影響任何外部儲存的結果 (例如 BigQuery)。

控制台

  1. 在 Google Cloud 控制台中,前往「Sensitive Data Protection」頁面。

    前往 Sensitive Data Protection

  2. 按一下「檢查」分頁標籤,然後按一下「檢查工作」子分頁標籤。 Google Cloud 控制台隨即會顯示目前專案的所有工作清單。

  3. 在要刪除的工作觸發條件的「Actions」(動作) 欄中,按一下「更多動作」選單 (垂直排列的三個圓點) ,然後點選「Delete」(刪除)

或者,從工作清單中,按一下要刪除的工作 ID。在工作的詳細資料頁面中,按一下「刪除」

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using System;
using Google.Cloud.Dlp.V2;

public class JobsDelete
{
    public static void DeleteJob(string jobName)
    {
        var dlp = DlpServiceClient.Create();

        dlp.DeleteDlpJob(new DeleteDlpJobRequest
        {
            Name = jobName
        });

        Console.WriteLine($"Successfully deleted job {jobName}.");
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// deleteJob deletes the job with the given name.
func deleteJob(w io.Writer, jobName string) error {
	// jobName := "job-example"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()
	req := &dlppb.DeleteDlpJobRequest{
		Name: jobName,
	}
	if err = client.DeleteDlpJob(ctx, req); err != nil {
		return fmt.Errorf("DeleteDlpJob: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted job")
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DeleteDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJobName;
import java.io.IOException;

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

  // Deletes a DLP Job with the given jobId
  public static void deleteJobs(String projectId, String jobId) 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()) {

      // Construct the complete job name from the projectId and jobId
      DlpJobName jobName = DlpJobName.of(projectId, jobId);

      // Construct the job deletion request to be sent by the client.
      DeleteDlpJobRequest deleteDlpJobRequest =
          DeleteDlpJobRequest.newBuilder().setName(jobName.toString()).build();

      // Send the job deletion request
      dlpServiceClient.deleteDlpJob(deleteDlpJobRequest);
      System.out.println("Job deleted successfully.");
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The name of the job whose results should be deleted
// Parent project ID is automatically extracted from this parameter
// const jobName = 'projects/my-project/dlpJobs/X-#####'

function deleteJob() {
  // Construct job deletion request
  const request = {
    name: jobName,
  };

  // Run job deletion request
  dlp
    .deleteDlpJob(request)
    .then(() => {
      console.log(`Successfully deleted job ${jobName}.`);
    })
    .catch(err => {
      console.log(`Error in deleteJob: ${err.message || err}`);
    });
}

deleteJob();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\DeleteDlpJobRequest;

/**
 * Delete results of a Data Loss Prevention API job
 *
 * @param string $jobId The name of the job whose results should be deleted
 */
function delete_job(string $jobId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run job-deletion request
    // The Parent project ID is automatically extracted from this parameter
    $deleteDlpJobRequest = (new DeleteDlpJobRequest())
        ->setName($jobId);
    $dlp->deleteDlpJob($deleteDlpJobRequest);

    // Print status
    printf('Successfully deleted job %s' . PHP_EOL, $jobId);
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import google.cloud.dlp


def delete_dlp_job(project: str, job_name: str) -> None:
    """Uses the Data Loss Prevention API to delete a long-running DLP job.
    Args:
        project: The project id to use as a parent resource.
        job_name: The name of the DlpJob resource to be deleted.

    Returns:
        None; the response from the API is printed to the terminal.
    """

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

    # Convert the project id and job name into a full resource id.
    name = f"projects/{project}/dlpJobs/{job_name}"

    # Call the API to delete job.
    dlp.delete_dlp_job(request={"name": name})

    print(f"Successfully deleted {job_name}")

REST

如要從目前專案中刪除工作,請將 DELETE 要求傳送至 dlpJobs 端點,如下所示。將 [JOB-IDENTIFIER] 欄位替換為工作 ID,開頭為 i-

網址:

DELETE https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/dlpJobs/[JOB-IDENTIFIER]?key={YOUR_API_KEY}

如果要求成功完成,DLP API 將傳回成功的回應。如要確認工作已成功刪除,請列出所有工作

如要快速嘗試,可以使用下方內嵌的 API Explorer。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

刪除工作觸發條件

控制台

  1. 在 Google Cloud 控制台中,前往「Sensitive Data Protection」頁面。

    前往 Sensitive Data Protection

    在「檢查」分頁的「工作觸發條件」子分頁中,主控台會顯示目前專案所有工作觸發條件的清單。

  2. 在要刪除的工作觸發條件的「Actions」(動作) 欄中,按一下「更多動作」選單 (垂直排列的三個圓點) ,然後點選「Delete」(刪除)

或者,從工作觸發條件的清單中,按一下您要刪除的工作觸發條件名稱。在工作觸發條件的詳細資料頁面中,按一下 [Delete] (刪除)

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Cloud.Dlp.V2;
using System;

public class TriggersDelete
{

    public static void Delete(string triggerName)
    {
        var dlp = DlpServiceClient.Create();

        dlp.DeleteJobTrigger(
            new DeleteJobTriggerRequest
            {
                Name = triggerName
            });

        Console.WriteLine($"Successfully deleted trigger {triggerName}.");
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// deleteTrigger deletes the given trigger.
func deleteTrigger(w io.Writer, triggerID string) error {
	// triggerID := "my-trigger"

	ctx := context.Background()

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

	req := &dlppb.DeleteJobTriggerRequest{
		Name: triggerID,
	}

	if err := client.DeleteJobTrigger(ctx, req); err != nil {
		return fmt.Errorf("DeleteJobTrigger: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted trigger %v", triggerID)
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DeleteJobTriggerRequest;
import com.google.privacy.dlp.v2.ProjectJobTriggerName;
import java.io.IOException;

class TriggersDelete {

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

  public static void deleteTrigger(String projectId, String triggerId) 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()) {

      // Get the full trigger name from the given triggerId and ProjectId
      ProjectJobTriggerName triggerName = ProjectJobTriggerName.of(projectId, triggerId);

      // Construct the trigger deletion request to be sent by the client
      DeleteJobTriggerRequest deleteJobTriggerRequest =
          DeleteJobTriggerRequest.newBuilder().setName(triggerName.toString()).build();

      // Send the trigger deletion request
      dlpServiceClient.deleteJobTrigger(deleteJobTriggerRequest);
      System.out.println("Trigger deleted: " + triggerName.toString());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project'

// The name of the trigger to be deleted
// Parent project ID is automatically extracted from this parameter
// const triggerId = 'projects/my-project/triggers/my-trigger';

async function deleteTrigger() {
  // Construct trigger deletion request
  const request = {
    name: triggerId,
  };

  // Run trigger deletion request
  await dlp.deleteJobTrigger(request);
  console.log(`Successfully deleted trigger ${triggerId}.`);
}

deleteTrigger();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\DeleteJobTriggerRequest;

/**
 * Delete a Data Loss Prevention API job trigger.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 * @param string $triggerId         The name of the trigger to be deleted.
 */
function delete_trigger(string $callingProjectId, string $triggerId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run request
    // The Parent project ID is automatically extracted from this parameter
    $triggerName = "projects/$callingProjectId/locations/global/jobTriggers/$triggerId";
    $deleteJobTriggerRequest = (new DeleteJobTriggerRequest())
        ->setName($triggerName);
    $dlp->deleteJobTrigger($deleteJobTriggerRequest);

    // Print the results
    printf('Successfully deleted trigger %s' . PHP_EOL, $triggerName);
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import google.cloud.dlp


def delete_trigger(project: str, trigger_id: str) -> None:
    """Deletes a Data Loss Prevention API trigger.
    Args:
        project: The id of the Google Cloud project which owns the trigger.
        trigger_id: The id of the trigger to delete.
    Returns:
        None; the response from the API is printed to the terminal.
    """

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

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

    # Combine the trigger id with the parent id.
    trigger_resource = f"{parent}/jobTriggers/{trigger_id}"

    # Call the API.
    dlp.delete_job_trigger(request={"name": trigger_resource})

    print(f"Trigger {trigger_resource} successfully deleted.")

REST

如要從目前專案中刪除工作觸發條件,請將 DELETE 要求傳送至 jobTriggers 端點,如下所示。將 [JOB-TRIGGER-NAME] 欄位替換為工作觸發條件的名稱。

網址:

DELETE https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/jobTriggers/[JOB-TRIGGER-NAME]?key={YOUR_API_KEY}

如果要求成功完成,DLP API 將傳回成功的回應。如要確認工作觸發條件已成功刪除,請列出所有工作觸發條件

如要快速嘗試,可以使用下方內嵌的 API Explorer。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

取得工作

如要從專案取得工作 (包括結果),請按照下列步驟操作:這項作業不會影響任何外部儲存的結果 (例如 BigQuery)。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Cloud.Dlp.V2;
using System;

public class JobsGet
{
    public static DlpJob GetDlpJob(string jobName)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.GetDlpJob(jobName);

        Console.WriteLine($"Job: {response.Name} status: {response.State}");

        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// jobsGet gets an inspection job using jobName
func jobsGet(w io.Writer, projectID string, jobName string) error {
	// projectId := "my-project-id"
	// jobName := "your-job-id"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Construct the request to be sent by the client.
	req := &dlppb.GetDlpJobRequest{
		Name: jobName,
	}

	// Send the request.
	resp, err := client.GetDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the results.
	fmt.Fprintf(w, "Job Name: %v Job Status: %v", resp.Name, resp.State)
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DlpJobName;
import com.google.privacy.dlp.v2.GetDlpJobRequest;
import java.io.IOException;

public class JobsGet {

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

  // Gets a DLP Job with the given jobId
  public static void getJobs(String projectId, String jobId) 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()) {

      // Construct the complete job name from the projectId and jobId
      DlpJobName jobName = DlpJobName.of(projectId, jobId);

      // Construct the get job request to be sent by the client.
      GetDlpJobRequest getDlpJobRequest =
          GetDlpJobRequest.newBuilder().setName(jobName.toString()).build();

      // Send the get job request
      dlpServiceClient.getDlpJob(getDlpJobRequest);
      System.out.println("Job got successfully.");
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// Job name to look for
// const jobName = 'your-job-name';

async function getJob() {
  // Construct request for finding job using job name.
  const request = {
    name: jobName,
  };

  // Send the request and receive response from the service
  const [job] = await dlp.getDlpJob(request);

  // Print results.
  console.log(`Job ${job.name} status: ${job.state}`);
}

getJob();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\GetDlpJobRequest;

/**
 * Get DLP inspection job.
 * @param string $jobName           Dlp job name
 */
function get_job(
    string $jobName
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();
    try {
        // Send the get job request
        $getDlpJobRequest = (new GetDlpJobRequest())
            ->setName($jobName);
        $response = $dlp->getDlpJob($getDlpJobRequest);
        printf('Job %s status: %s' . PHP_EOL, $response->getName(), $response->getState());
    } finally {
        $dlp->close();
    }
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import google.cloud.dlp


def get_dlp_job(project: str, job_name: str) -> None:
    """Uses the Data Loss Prevention API to retrieve a DLP job.
    Args:
        project: The project id to use as a parent resource.
        job_name: The name of the DlpJob resource to be retrieved.
    """

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

    # Convert the project id and job name into a full resource id.
    job_name = f"projects/{project}/locations/global/dlpJobs/{job_name}"

    # Call the API
    response = dlp.get_dlp_job(request={"name": job_name})

    print(f"Job: {response.name} Status: {response.state}")

REST

如要從目前專案取得工作,請將 GET 要求傳送至 dlpJobs 端點,如下所示。將 [JOB-IDENTIFIER] 欄位替換為工作 ID,開頭為 i-

網址:

GET https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/dlpJobs/[JOB-IDENTIFIER]?key={YOUR_API_KEY}

如果要求成功完成,DLP API 將傳回成功的回應。

如要快速嘗試,可以使用下方內嵌的 API Explorer。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

強制立即執行工作觸發條件

建立工作觸發條件後,您可以啟用觸發條件,強制立即執行觸發條件以進行測試。如要進行這項操作,請執行下列指令:

curl --request POST \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-Goog-User-Project: PROJECT_ID" \
    'https://dlp.googleapis.com/v2/JOB_TRIGGER_NAME:activate'

更改下列內容:

更新現有工作觸發條件

除了建立、列出和刪除工作觸發條件之外,您還可以更新現有工作觸發條件。如要變更現有工作觸發條件的設定:

控制台

  1. 在 Google Cloud 控制台中,前往「Sensitive Data Protection」頁面。

    前往 Sensitive Data Protection

  2. 按一下「檢查」分頁標籤,然後按一下「工作觸發條件」子分頁標籤。

    主控台會顯示目前專案所有工作觸發條件的清單。

  3. 在要刪除的工作觸發條件的「Actions」(動作) 欄中,按一下「More」(更多) ,然後按一下「View details」(查看詳細資料)

  4. 在工作觸發條件詳細資料頁面中,按一下 [Edit] (編輯)

  5. 在「Edit trigger」(編輯觸發條件) 頁面中,您可以變更輸入資料的位置;偵測詳細資料,例如範本、infoType 或可能性;掃描後採取的動作以及工作觸發條件的排程。變更完成後,按一下 [Save] (儲存)

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Cloud.Dlp.V2;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;

public class TriggersUpdate
{
    public static JobTrigger UpdateJob(
        string projectId,
        string triggerId,
        IEnumerable<InfoType> infoTypes = null,
        Likelihood minLikelihood = Likelihood.Likely)
    {
        // Instantiate the client.
        var dlp = DlpServiceClient.Create();

        // Construct the update job trigger request object by providing the trigger name,
        // job trigger object which will specify the type of info to be inspected and
        // update mask object which specifies the field to be updated.
        // Refer to https://cloud.google.com/dlp/docs/reference/rest/v2/Container for specifying the paths in container object.
        var request = new UpdateJobTriggerRequest
        {
            JobTriggerName = new JobTriggerName(projectId, triggerId),
            JobTrigger = new JobTrigger
            {
                InspectJob = new InspectJobConfig
                {
                    InspectConfig = new InspectConfig
                    {
                        InfoTypes =
                        {
                            infoTypes ?? new InfoType[]
                            {
                                new InfoType { Name = "US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER" }
                            }
                        },
                        MinLikelihood = minLikelihood
                    }
                }
            },
            // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
            // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
            UpdateMask = new FieldMask
            {
                Paths =
                {
                    "inspect_job.inspect_config.info_types",
                    "inspect_job.inspect_config.min_likelihood"
                }
            }
        };

        // Call the API.
        JobTrigger response = dlp.UpdateJobTrigger(request);

        // Inspect the result.
        Console.WriteLine($"Job Trigger Name: {response.Name}");
        Console.WriteLine($"InfoType updated: {response.InspectJob.InspectConfig.InfoTypes[0]}");
        Console.WriteLine($"Likelihood updated: {response.InspectJob.InspectConfig.MinLikelihood}");
        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateTrigger updates an existing job trigger in Google Cloud Data Loss Prevention (DLP).
// It modifies the configuration of the specified job trigger with the provided updated settings.
func updateTrigger(w io.Writer, jobTriggerName string) error {
	// jobTriggerName := "your-job-trigger-name" (projects/<projectID>/locations/global/jobTriggers/my-trigger)

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	infoType := &dlppb.InfoType{
		Name: "PERSON_NAME",
	}

	// Specify the inspectConfig that represents the configuration settings for inspecting sensitive data in
	// DLP API. It includes detection types, custom info types, inspection methods, and actions
	// to be taken on detection.
	inspectConfig := &dlppb.InspectConfig{
		InfoTypes: []*dlppb.InfoType{
			infoType,
		},
		MinLikelihood: dlppb.Likelihood_LIKELY,
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		InspectConfig: inspectConfig,
	}

	// Specify the jobTrigger that represents a DLP job trigger configuration.
	// It defines the conditions, actions, and schedule for executing inspections
	// on sensitive data in the specified data storage.
	jobTrigger := &dlppb.JobTrigger{
		Job: &dlppb.JobTrigger_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// fieldMask represents a set of fields to be included in an update operation.
	// It is used to specify which fields of a resource should be updated.
	updateMask := &fieldmaskpb.FieldMask{
		Paths: []string{"inspect_job.inspect_config.info_types", "inspect_job.inspect_config.min_likelihood"},
	}

	// Combine configurations into a request for the service.
	req := &dlppb.UpdateJobTriggerRequest{
		Name:       jobTriggerName,
		JobTrigger: jobTrigger,
		UpdateMask: updateMask,
	}

	// Send the scan request and process the response
	resp, err := client.UpdateJobTrigger(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "Successfully Updated trigger: %v", resp)
	return nil

}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.JobTrigger;
import com.google.privacy.dlp.v2.JobTriggerName;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.UpdateJobTriggerRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class TriggersPatch {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.

    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The name of the job trigger to be updated.
    String jobTriggerName = "your-job-trigger-name";
    patchTrigger(projectId, jobTriggerName);
  }

  // Uses the Data Loss Prevention API to update an existing job trigger.
  public static void patchTrigger(String projectId, String jobTriggerName) 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()) {

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      InfoType infoType = InfoType.newBuilder().setName("PERSON_NAME").build();

      InspectConfig inspectConfig = InspectConfig.newBuilder()
              .addInfoTypes(infoType)
              .setMinLikelihood(Likelihood.LIKELY)
              .build();

      InspectJobConfig inspectJobConfig = InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .build();

      JobTrigger jobTrigger = JobTrigger.newBuilder()
              .setInspectJob(inspectJobConfig)
              .build();

      // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
      // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
      FieldMask fieldMask = FieldMask.newBuilder()
              .addPaths("inspect_job.inspect_config.info_types")
              .addPaths("inspect_job.inspect_config.min_likelihood")
              .build();

      // Update the job trigger with the new configuration.
      UpdateJobTriggerRequest updateJobTriggerRequest = UpdateJobTriggerRequest.newBuilder()
              .setName(JobTriggerName.of(projectId, jobTriggerName).toString())
              .setJobTrigger(jobTrigger)
              .setUpdateMask(fieldMask)
              .build();

      // Call the API to update the job trigger.
      JobTrigger updatedJobTrigger = dlpServiceClient.updateJobTrigger(updateJobTriggerRequest);

      System.out.println("Job Trigger Name: " + updatedJobTrigger.getName());
      System.out.println(
          "InfoType updated: "
              + updatedJobTrigger.getInspectJob().getInspectConfig().getInfoTypes(0).getName());
      System.out.println(
          "Likelihood updated: "
              + updatedJobTrigger.getInspectJob().getInspectConfig().getMinLikelihood());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlpClient = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The job trigger ID to run the API call under
// const jobTriggerName = 'your-job-trigger-name';

async function updateTrigger() {
  // Construct inspect configuration to match PERSON_NAME infotype
  const inspectConfig = {
    infoTypes: [{name: 'PERSON_NAME'}],
    minLikelihood: 'LIKELY',
  };

  // Configure the job trigger we want to update.
  const jobTrigger = {inspectJob: {inspectConfig}};

  const updateMask = {
    paths: [
      'inspect_job.inspect_config.info_types',
      'inspect_job.inspect_config.min_likelihood',
    ],
  };

  // Combine configurations into a request for the service.
  const request = {
    name: `projects/${projectId}/jobTriggers/${jobTriggerName}`,
    jobTrigger,
    updateMask,
  };

  // Send the request and receive response from the service
  const [updatedJobTrigger] = await dlpClient.updateJobTrigger(request);

  // Print the results
  console.log(`Updated Trigger: ${JSON.stringify(updatedJobTrigger)}`);
}
updateTrigger(projectId, jobTriggerName);

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\JobTrigger;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\UpdateJobTriggerRequest;
use Google\Protobuf\FieldMask;

/**
 * Update an existing job trigger.
 *
 * @param string $callingProjectId  The Google Cloud Project ID to run the API call under.
 * @param string $jobTriggerName    The job trigger name to update.
 *
 */
function update_trigger(
    string $callingProjectId,
    string $jobTriggerName
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Configure the inspectConfig.
    $inspectConfig = (new InspectConfig())
        ->setInfoTypes([
            (new InfoType())
                ->setName('US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER')
        ])
        ->setMinLikelihood(Likelihood::LIKELY);

    // Configure the Job Trigger we want the service to perform.
    $jobTrigger = (new JobTrigger())
        ->setInspectJob((new InspectJobConfig())
            ->setInspectConfig($inspectConfig));

    // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
    // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
    $fieldMask = (new FieldMask())
        ->setPaths([
            'inspect_job.inspect_config.info_types',
            'inspect_job.inspect_config.min_likelihood'
        ]);

    // Send the update job trigger request and process the response.
    $name = "projects/$callingProjectId/locations/global/jobTriggers/" . $jobTriggerName;
    $updateJobTriggerRequest = (new UpdateJobTriggerRequest())
        ->setName($name)
        ->setJobTrigger($jobTrigger)
        ->setUpdateMask($fieldMask);

    $response = $dlp->updateJobTrigger($updateJobTriggerRequest);

    // Print results.
    printf('Successfully update trigger %s' . PHP_EOL, $response->getName());
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from typing import List

import google.cloud.dlp


def update_trigger(
    project: str,
    info_types: List[str],
    trigger_id: str,
) -> None:
    """Uses the Data Loss Prevention API to update an existing job trigger.
    Args:
        project: The Google Cloud project id to use as a parent resource
        info_types: A list of strings representing infoTypes to update trigger with.
            A full list of infoType categories can be fetched from the API.
        trigger_id: The id of job trigger which needs to be updated.
    """

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

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Specify fields of the jobTrigger resource to be updated when the
    # job trigger is modified.
    job_trigger = {
        "inspect_job": {
            "inspect_config": {
                "info_types": info_types,
                "min_likelihood": google.cloud.dlp_v2.Likelihood.LIKELY,
            }
        }
    }

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

    # Call the API.
    # Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
    # for constructing the field mask paths.
    response = dlp.update_job_trigger(
        request={
            "name": trigger_name,
            "job_trigger": job_trigger,
            "update_mask": {
                "paths": [
                    "inspect_job.inspect_config.info_types",
                    "inspect_job.inspect_config.min_likelihood",
                ]
            },
        }
    )

    # Print out the result.
    print(f"Successfully updated trigger: {response.name}")
    print(
        f"Updated InfoType: {response.inspect_job.inspect_config.info_types[0].name}"
        f" \nUpdates Likelihood: {response.inspect_job.inspect_config.min_likelihood}\n",
    )

REST

使用 projects.jobTriggers.patch 方法將新的 JobTrigger 值傳送至 DLP API,即可更新指定工作觸發條件中的這些值。

例如,請考量下列簡單的工作觸發條件。此 JSON 代表工作觸發條件,並且會在將 GET 要求傳送至目前專案的工作觸發條件端點之後傳回。

JSON 輸出:

{
  "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://dlptesting/*"
        },
        "fileTypes":[
          "FILE_TYPE_UNSPECIFIED"
        ],
        "filesLimitPercent":100
      },
      "timespanConfig":{
        "enableAutoPopulationOfTimespanConfig":true
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"US_SOCIAL_SECURITY_NUMBER"
        }
      ],
      "minLikelihood":"POSSIBLE",
      "limits":{

      }
    },
    "actions":[
      {
        "jobNotificationEmails":{

        }
      }
    ]
  },
  "triggers":[
    {
      "schedule":{
        "recurrencePeriodDuration":"86400s"
      }
    }
  ],
  "createTime":"2019-03-06T21:19:45.774841Z",
  "updateTime":"2019-03-06T21:19:45.774841Z",
  "status":"HEALTHY"
}

透過 PATCH 要求將下列 JSON 傳送至指定端點時,該 JSON 會以要掃描的新 infoType 和新的最低可能性,更新指定工作觸發條件。請注意,您還必須指定 updateMask 屬性,且其值的格式為 FieldMask

JSON 輸入:

PATCH https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]?key={YOUR_API_KEY}

{
  "jobTrigger":{
    "inspectJob":{
      "inspectConfig":{
        "infoTypes":[
          {
            "name":"US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER"
          }
        ],
        "minLikelihood":"LIKELY"
      }
    }
  },
  "updateMask":"inspectJob(inspectConfig(infoTypes,minLikelihood))"
}

在您將此 JSON 傳送至指定網址之後,JSON 會傳回下列內容,表示更新的工作觸發條件。請注意,原始 infoType 和可能性值已由新值取代。

JSON 輸出:

{
  "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://dlptesting/*"
        },
        "fileTypes":[
          "FILE_TYPE_UNSPECIFIED"
        ],
        "filesLimitPercent":100
      },
      "timespanConfig":{
        "enableAutoPopulationOfTimespanConfig":true
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER"
        }
      ],
      "minLikelihood":"LIKELY",
      "limits":{

      }
    },
    "actions":[
      {
        "jobNotificationEmails":{

        }
      }
    ]
  },
  "triggers":[
    {
      "schedule":{
        "recurrencePeriodDuration":"86400s"
      }
    }
  ],
  "createTime":"2019-03-06T21:19:45.774841Z",
  "updateTime":"2019-03-06T21:27:01.650183Z",
  "lastRunTime":"1970-01-01T00:00:00Z",
  "status":"HEALTHY"
}

如要快速嘗試,可以使用下方內嵌的 API Explorer。如要瞭解如何透過 JSON 將要求傳送至 DLP API 的一般資訊,請參閱 JSON 快速入門

工作延遲

作業和作業觸發程序不提供服務等級目標 (SLO) 保證。延遲時間會受到多種因素影響,包括要掃描的資料量、掃描的儲存空間存放區、掃描的 infoType 類型和數量、處理作業的區域,以及該區域可用的運算資源。因此,無法預先判斷檢查工作的延遲時間。

如要縮短工作延遲時間,可以嘗試下列方法:

  • 如果工作或工作觸發條件提供取樣功能,請啟用這項功能。
  • 避免啟用不需要的 infoType。雖然下列 infoType 在特定情境中很有用,但與不含這些 infoType 的要求相比,要求執行速度可能會慢上許多:

    • PERSON_NAME
    • FEMALE_NAME
    • MALE_NAME
    • FIRST_NAME
    • LAST_NAME
    • DATE_OF_BIRTH
    • LOCATION
    • STREET_ADDRESS
    • ORGANIZATION_NAME
  • 請務必明確指定 infoType。請勿使用空白的 infoTypes 清單。

  • 請盡可能使用其他處理區域。

如果嘗試上述方法後,作業仍有延遲問題,請考慮使用 content.inspectcontent.deidentify 要求,而非作業。這些方法適用於服務水準協議。詳情請參閱《Sensitive Data Protection 服務水準協議》。

限制只掃描新內容

您可以設定工作觸發條件,針對儲存在 Cloud StorageBigQuery 中的檔案,自動設定時間範圍日期。將 TimespanConfig 物件設為自動填入後,Sensitive Data Protection 只會掃描上次執行觸發條件後新增或修改的資料:

...
  timespan_config {
        enable_auto_population_of_timespan_config: true
      }
...

如為 BigQuery 檢查,則只會掃描存在時間滿三小時的資料列。請參閱與這項作業相關的已知問題

檔案上傳時觸發工作

除了內建於 Sensitive Data Protection 的工作觸發條件支援以外,Google Cloud 還有各種其他元件,可用於整合或觸發 Sensitive Data Protection 工作。舉例來說,您可以使用 Cloud Run 函式,在每次檔案上傳至 Cloud Storage 時觸發 Sensitive Data Protection 掃描。

如要瞭解如何設定這項作業,請參閱「自動分類上傳至 Cloud Storage 的資料」一文。

成功執行工作,但未檢查任何資料

即使沒有掃描任何資料,工作仍可能順利完成。以下是可能導致這種情況的範例:

  • 工作設定為檢查特定資料資產 (例如現有但空白的檔案)。
  • 工作設定為檢查不存在或已不存在的資料資產。
  • 這項工作已設定為檢查空白的 Cloud Storage bucket。
  • 這項工作已設定為檢查儲存空間,且已停用遞迴掃描。 在頂層,值區只包含資料夾,而資料夾則包含檔案。
  • 這項工作設定為只檢查儲存空間中的特定檔案類型,但儲存空間中沒有任何這類檔案。
  • 這項工作已設定為只檢查新內容,但上次執行工作後沒有任何更新。

在 Google Cloud 控制台的「Job details」(工作詳細資料) 頁面中,「Bytes scanned」(掃描的位元組數) 欄位會顯示工作檢查的資料量。在 DLP API 中,processedBytes 欄位會指定檢查的資料量。

後續步驟