建立 Sensitive Data Protection 檢查範本

本主題將詳細說明如何建立新的檢查範本。如要快速瞭解如何使用Google Cloud 控制台建立新的檢查範本,請參閱「快速入門導覽課程:建立 Sensitive Data Protection 檢查範本」。

關於範本

您可以使用範本建立及保留設定資訊,以便與 Sensitive Data Protection 搭配使用。範本很適合用於將檢查內容和去識別化方式等設定資訊與要求的實作分離,範本可讓您重複使用設定,並確保使用者和資料集之間的一致性。此外,每當您更新範本時,使用該範本的所有工作觸發條件也會一併更新。

Sensitive Data Protection 支援檢查範本 (本主題會討論) 和去識別化範本 (請參閱「建立 Sensitive Data Protection 去識別化範本」)。

如要瞭解 Sensitive Data Protection 範本的概念,請參閱「範本」。

如要進一步瞭解可在檢查範本中指定的資訊類型 (infoTypes),請參閱「infoType 偵測工具參考資料」。

建立新的檢查範本

控制台

前往 Google Cloud 控制台的「Create template」(建立範本) 頁面。

前往「建立範本」

「Create template」(建立範本) 頁面包含下列部分:

定義範本

在「定義範本」下方,輸入檢查範本的 ID。執行工作、建立工作觸發條件等時,您會使用這個名稱來參照範本。您可以使用英文字母、數字和連字號。您也可以視需要輸入更易於理解的顯示名稱和說明,以便記住範本的用途。

在「Resource location」(資源位置) 欄位中,選取要檢查的資料儲存區域。您建立的檢查範本也會儲存在這個區域。如要在任何區域使用新的檢查範本,請選取「Global (any region)」(全球 (任何區域))。

設定偵測作業

接著,您要選擇 infoType 和其他選項,設定 Sensitive Data Protection 偵測內容的方式。

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

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

如要進一步瞭解如何在本節中管理內建和自訂 infoType,請參閱「透過 Google Cloud 控制台管理 infoType」。

檢查規則集

檢查規則集可讓您使用結構定義規則,自訂內建和自訂 infoType 偵測工具。檢查規則類型如下:

如要新增規則集,請先在「InfoTypes」InfoTypes部分指定一或多個內建或自訂 infoType 偵測工具。選取規則集修改的所有 infoType 偵測工具 (「目標」infoType),或用於評估的 infoType 偵測工具 (「情境」infoType)。接著,請按照下列步驟操作:

  1. 按一下「新增規則集」。
  2. 在「Choose target infoTypes」(選擇目標 infoType) 欄位中,選取符合規則時,規則集會修改的 infoType。
  3. 按一下「新增規則」,開啟包含「啟動字詞規則」、「排除規則」和「調整規則」等選項的選單。

如要建立啟動字詞規則,請選取「啟動字詞規則」。接著,按照下列步驟操作:

  1. 在「Hotword」(熱字) 欄位中,輸入 Sensitive Data Protection 要尋找的規則運算式。
  2. 在「Hotword proximity」(熱字鄰近性) 選單中,選取輸入的熱字是在所選 infoType 之前或之後。
  3. 在「Hotword distance from infoType」(與 infoType 的熱字距離) 中,輸入熱字與所選 infoType 之間的大約字元數。
  4. 在「Confidence level adjustment」(信賴水準調整) 中,選取要為相符項目指派固定的可能性等級,還是要將預設可能性等級提高或降低特定程度。

如要建立排除規則,請選取「Exclusion rule」(排除規則),然後選取要建立的排除規則類型,例如「Regular expression」(規則運算式)。接著,按照下列步驟操作:

  1. 視所選排除規則類型而定,輸入必須找到的規則運算式、詞組、啟動字詞或結構定義 infoType,才能套用規則。
  2. 視您選取的排除規則類型而定,設定比對類型或圖片包含類型:
    • 如果您選取文字排除規則,請選取下列其中一種比對類型:
      • 完全相符:發現項目必須與您提供的文字或情境 infoType 完全相符。
      • 部分相符:發現項目的子字串必須與您提供的文字或內容 infoType 相符。
      • 反向比對:發現項目不得與您提供的文字或內容 infoType 相符。
    • 如果選取以圖片為基礎的排除規則,請選取目標和背景資訊 infoType 之間所需的空間關係。舉例來說,如果選取「Encloses」,情境發現項目必須包含目標發現項目,規則才會套用。

如要建立調整規則,請選取「調整規則」和調整規則類型,例如「依據映像檔發現項目調整」。接著,按照下列步驟操作:

  1. 在「Context infoTypes」(情境 infoType) 欄位中,選取為目標發現項目提供情境的 infoType 偵測工具。Sensitive Data Protection 會使用背景資訊 infoType,評估是否必須調整目標 infoType。
  2. 在「Minimum likelihood」(可能性下限) 欄位中,選取情境 infoType 可具備且仍會觸發調整規則的最低可能性等級。如果偵測到的任何內容發現項目可能性值低於這個值,Sensitive Data Protection 就不會調整目標發現項目的可能性。
  3. 如果是圖片發現項目,請在「Image containment type」(圖片包含類型) 欄位中,選取目標和背景資訊 infoType 之間所需的空間關係。舉例來說,如果選取「Encloses」,情境發現項目必須包含目標發現項目,規則才會套用。
  4. 在「Likelihood」(可能性) 欄位中,選取要指派給目標發現項目的新可能性等級。

您可以新增更多規則集,進一步修正掃描結果。

可信度門檻

每當 Sensitive Data Protection 偵測到可能與機密資料相符的項目時,就會指派「可能性」值,範圍從「極不可能」到「極有可能」。在這裡設定可能性值,即代表指示 Sensitive Data Protection 只比對符合或高於該可能性值的資料。

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

完成之後,按一下 [Create] (建立) 即可建立範本。系統隨即會顯示範本的摘要資訊頁面。

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

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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


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

public class InspectTemplateCreate
{
    public static InspectTemplate Create(
        string projectId,
        string templateId,
        string displayName,
        string description,
        Likelihood likelihood,
        int maxFindings,
        bool includeQuote)
    {
        var client = DlpServiceClient.Create();

        var request = new CreateInspectTemplateRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            InspectTemplate = new InspectTemplate
            {
                DisplayName = displayName,
                Description = description,
                InspectConfig = new InspectConfig
                {
                    MinLikelihood = likelihood,
                    Limits = new InspectConfig.Types.FindingLimits
                    {
                        MaxFindingsPerRequest = maxFindings
                    },
                    IncludeQuote = includeQuote
                },
            },
            TemplateId = templateId
        };

        var response = client.CreateInspectTemplate(request);

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

        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

import (
	"context"
	"fmt"
	"io"

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

// createInspectTemplate creates a template with the given configuration.
func createInspectTemplate(w io.Writer, projectID string, templateID, displayName, description string, infoTypeNames []string) error {
	// projectID := "my-project-id"
	// templateID := "my-template"
	// displayName := "My Template"
	// description := "My template description"
	// 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.CreateInspectTemplateRequest{
		Parent:     fmt.Sprintf("projects/%s/locations/global", projectID),
		TemplateId: templateID,
		InspectTemplate: &dlppb.InspectTemplate{
			DisplayName: displayName,
			Description: description,
			InspectConfig: &dlppb.InspectConfig{
				InfoTypes:     infoTypes,
				MinLikelihood: dlppb.Likelihood_POSSIBLE,
				Limits: &dlppb.InspectConfig_FindingLimits{
					MaxFindingsPerRequest: 10,
				},
			},
		},
	}
	// Send the request.
	resp, err := client.CreateInspectTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateInspectTemplate: %w", err)
	}
	// Print the result.
	fmt.Fprintf(w, "Successfully created inspect template: %v", resp.GetName())
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CreateInspectTemplateRequest;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectTemplate;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class TemplatesCreate {

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

  // Creates a template to persist configuration information
  public static void createInspectTemplate(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()) {
      // 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());

      // Construct the inspection configuration for the template
      InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).build();

      // Optionally set a display name and a description for the template
      String displayName = "Inspection Config Template";
      String description = "Save configuration for future inspection jobs";

      // Build the template
      InspectTemplate inspectTemplate =
          InspectTemplate.newBuilder()
              .setInspectConfig(inspectConfig)
              .setDisplayName(displayName)
              .setDescription(description)
              .build();

      // Create the request to be sent by the client
      CreateInspectTemplateRequest createInspectTemplateRequest =
          CreateInspectTemplateRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectTemplate(inspectTemplate)
              .build();

      // Send the request to the API and process the response
      InspectTemplate response =
          dlpServiceClient.createInspectTemplate(createInspectTemplateRequest);
      System.out.printf("Template created: %s", response.getName());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「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 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;

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

// Whether to include the matching string
// const includeQuote = true;

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

// (Optional) The human-readable name to give the template
// const displayName = 'My template';

async function createInspectTemplate() {
  // Construct the inspection configuration for the template
  const inspectConfig = {
    infoTypes: infoTypes,
    minLikelihood: minLikelihood,
    includeQuote: includeQuote,
    limits: {
      maxFindingsPerRequest: maxFindings,
    },
  };

  // Construct template-creation request
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectTemplate: {
      inspectConfig: inspectConfig,
      displayName: displayName,
    },
    templateId: templateId,
  };

  const [response] = await dlp.createInspectTemplate(request);
  const templateName = response.name;
  console.log(`Successfully created template ${templateName}.`);
}
createInspectTemplate();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CreateInspectTemplateRequest;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\InspectTemplate;
use Google\Cloud\Dlp\V2\Likelihood;

/**
 * Create a new DLP inspection configuration template.
 *
 * @param string $callingProjectId project ID to run the API call under
 * @param string $templateId       name of the template to be created
 * @param string $displayName      (Optional) The human-readable name to give the template
 * @param string $description      (Optional) A description for the trigger to be created
 * @param int    $maxFindings      (Optional) The maximum number of findings to report per request (0 = server maximum)
 */
function create_inspect_template(
    string $callingProjectId,
    string $templateId,
    string $displayName = '',
    string $description = '',
    int $maxFindings = 0
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

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

    // Whether to include the matching string in the response
    $includeQuote = true;

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

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

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

    // Construct inspection template
    $inspectTemplate = (new InspectTemplate())
        ->setInspectConfig($inspectConfig)
        ->setDisplayName($displayName)
        ->setDescription($description);

    // Run request
    $parent = "projects/$callingProjectId/locations/global";
    $createInspectTemplateRequest = (new CreateInspectTemplateRequest())
        ->setParent($parent)
        ->setInspectTemplate($inspectTemplate)
        ->setTemplateId($templateId);
    $template = $dlp->createInspectTemplate($createInspectTemplateRequest);

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

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

from typing import List
from typing import Optional

import google.cloud.dlp


def create_inspect_template(
    project: str,
    info_types: List[str],
    template_id: Optional[str] = None,
    display_name: Optional[str] = None,
    min_likelihood: Optional[int] = None,
    max_findings: Optional[int] = None,
    include_quote: Optional[bool] = None,
) -> None:
    """Creates a Data Loss Prevention API inspect template.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        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.
        template_id: The id of the template. If omitted, an id will be randomly
            generated.
        display_name: The optional display name of the template.
        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.
        include_quote: Boolean for whether to display a quote of the detected
            information in the results.
    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,
        "include_quote": include_quote,
        "limits": {"max_findings_per_request": max_findings},
    }

    inspect_template = {
        "inspect_config": inspect_config,
        "display_name": display_name,
    }

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

    # Call the API.
    response = dlp.create_inspect_template(
        request={
            "parent": parent,
            "inspect_template": inspect_template,
            "template_id": template_id,
        }
    )

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

REST

檢查範本是可重複使用的檢查設定,加上一些中繼資料。在 API 術語中,InspectTemplate 物件實際上是 InspectConfig 物件,其中包含更多中繼資料欄位,例如顯示名稱和說明。因此,建立新檢查範本的基本步驟如下:

  1. 首先,請建立 InspectConfig 物件。
  2. 呼叫或 POST projects.inspectTemplates 或 organizations.inspectTemplates 資源的 create 方法,並在要求中加入 InspectTemplate 物件,其中包含顯示名稱、說明和 InspectConfig 物件。

退回的InspectTemplate可立即使用。您可以在其他呼叫或工作中,透過 name 參照該函式。您可以呼叫 *.inspectTemplates.list 方法,列出現有範本。如要查看特定範本,請呼叫 *.inspectTemplates.get 方法。請注意,您最多可以建立 1000 個範本。

如果您已使用 Sensitive Data Protection 檢查文字、圖片或結構化內容中的機密內容,則您已建立 InspectConfig 物件。再執行一個步驟,即可將其轉換為 InspectTemplate 物件。

下列 JSON 是可傳送至 projects.inspectTemplates.create 方法的範例。這個 JSON 會建立新的範本,並指定顯示名稱和說明,然後掃描 infoType PHONE_NUMBER 和 US_TOLLFREE_PHONE_NUMBER 的相符項目。這項檢查會找出最多 100 個可能性至少為 POSSIBLE 的相符項目,並為每個項目提供一段背景資訊。如要進一步瞭解可在檢查範本中指定的資訊類型 (infoTypes),請參閱「infoType 偵測工具參考資料」。

JSON 輸入:

POST https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/inspectTemplates
{
  "inspectTemplate":{
    "displayName":"Phone number inspection",
    "description":"Scans for phone numbers",
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"PHONE_NUMBER"
        },
        {
          "name":"US_TOLLFREE_PHONE_NUMBER"
        }
      ],
      "minLikelihood":"POSSIBLE",
      "limits":{
        "maxFindingsPerRequest":100
      },
      "includeQuote":true
    }
  }
}

JSON 輸出內容:

回應 JSON 會如下所示:

{
  "name":"projects/[PROJECT_ID]/inspectTemplates/[JOB_ID]",
  "displayName":"Phone number inspection",
  "description":"Scans for phone numbers",
  "createTime":"2018-11-30T07:26:28.164136Z",
  "updateTime":"2018-11-30T07:26:28.164136Z",
  "inspectConfig":{
    "infoTypes":[
      {
        "name":"PHONE_NUMBER"
      },
      {
        "name":"US_TOLLFREE_PHONE_NUMBER"
      }
    ],
    "minLikelihood":"POSSIBLE",
    "limits":{
      "maxFindingsPerRequest":100
    },
    "includeQuote":true
  }
}

如要快速試用,可以使用下方嵌入的 APIs Explorer。如需使用 JSON 向 DLP API 傳送要求的一般資訊,請參閱 JSON 快速入門導覽課程。

使用檢查範本

建立新的檢查範本後,您可以在建立新的檢查工作或工作觸發條件時使用該範本。只要更新範本,所有使用該範本的工作觸發條件都會一併更新。如需更多資訊 (包括程式碼範例),請參閱:

控制台

如要快速開始使用新範本,請按照「快速入門導覽課程:建立 Sensitive Data Protection 檢查範本」中的操作說明進行,並做出下列變更:

  • 在「Configure detection」(設定偵測) >「Templates」(範本) 部分,按一下「Template name」(範本名稱) 欄位,然後選取剛才建立的範本。

如要深入瞭解如何掃描內容,請參閱「建立及排定 Sensitive Data Protection 檢查工作」,並特別留意「設定偵測」一節。

REST

您可以在任何接受 inspectTemplateName 的地方,使用建立範本時指定的範本 ID,例如:

列出檢查範本

如何列出在目前的專案或機構中已建立的所有檢查範本:

控制台

  1. 在 Google Cloud 控制台中,前往 Sensitive Data Protection 的「Configuration」(設定) 頁面。

    前往「設定」

  2. 選取含有檢查範本的專案。

  3. 按一下 [Templates] (範本) 分頁標籤。

主控台隨即會列出目前專案的所有檢查範本。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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


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

public class InspectTemplateList
{
    public static PagedEnumerable<ListInspectTemplatesResponse, InspectTemplate> List(string projectId)
    {
        var client = DlpServiceClient.Create();

        var response = client.ListInspectTemplates(
            new ListInspectTemplatesRequest
            {
                Parent = new LocationName(projectId, "global").ToString(),
            }
        );

        // Uncomment to list templates
        //PrintTemplates(response);

        return response;
    }

    public static void PrintTemplates(PagedEnumerable<ListInspectTemplatesResponse, InspectTemplate> response)
    {
        foreach (var template in response)
        {
            Console.WriteLine($"Template {template.Name}:");
            Console.WriteLine($"\tDisplay Name: {template.DisplayName}");
            Console.WriteLine($"\tDescription: {template.Description}");
            Console.WriteLine($"\tCreated: {template.CreateTime}");
            Console.WriteLine($"\tUpdated: {template.UpdateTime}");
            Console.WriteLine("Configuration:");
            Console.WriteLine($"\tMin Likelihood: {template.InspectConfig?.MinLikelihood}");
            Console.WriteLine($"\tInclude quotes: {template.InspectConfig?.IncludeQuote}");
            Console.WriteLine($"\tMax findings per request: {template.InspectConfig?.Limits.MaxFindingsPerRequest}");
        }
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「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"
)

// listInspectTemplates lists the inspect templates in the project.
func listInspectTemplates(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.ListInspectTemplatesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}

	// Send the request and iterate over the results.
	it := client.ListInspectTemplates(ctx, req)
	for {
		t, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %w", err)
		}
		fmt.Fprintf(w, "Inspect template %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())
	}

	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.cloud.dlp.v2.DlpServiceClient.ListInspectTemplatesPagedResponse;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectTemplate;
import com.google.privacy.dlp.v2.ListInspectTemplatesRequest;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;

class TemplatesList {

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

  // Lists all templates associated with a given project
  public static void listInspectTemplates(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()) {

      // Create the request to be sent by the client
      ListInspectTemplatesRequest request =
          ListInspectTemplatesRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setPageSize(1)
              .build();

      // Send the request
      ListInspectTemplatesPagedResponse response = dlpServiceClient.listInspectTemplates(request);

      // Parse through and process the response
      System.out.println("Templates found:");
      for (InspectTemplate template : response.getPage().getResponse().getInspectTemplatesList()) {
        System.out.printf("Template name: %s\n", template.getName());
        if (template.getDisplayName() != null) {
          System.out.printf("\tDisplay name: %s \n", template.getDisplayName());
          System.out.printf("\tCreate time: %s \n", template.getCreateTime());
          System.out.printf("\tUpdate time: %s \n", template.getUpdateTime());

          // print inspection config
          InspectConfig inspectConfig = template.getInspectConfig();
          for (InfoType infoType : inspectConfig.getInfoTypesList()) {
            System.out.printf("\tInfoType: %s\n", infoType.getName());
          }
          System.out.printf("\tMin likelihood: %s\n", inspectConfig.getMinLikelihood());
          System.out.printf("\tLimits: %s\n", inspectConfig.getLimits().getMaxFindingsPerRequest());
        }
      }
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「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';

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

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

  // Run template-deletion request
  const [templates] = await dlp.listInspectTemplates(request);

  templates.forEach(template => {
    console.log(`Template ${template.name}`);
    if (template.displayName) {
      console.log(`  Display name: ${template.displayName}`);
    }

    console.log(`  Created: ${formatDate(template.createTime)}`);
    console.log(`  Updated: ${formatDate(template.updateTime)}`);

    const inspectConfig = template.inspectConfig;
    const infoTypes = inspectConfig.infoTypes.map(x => x.name);
    console.log('  InfoTypes:', infoTypes.join(' '));
    console.log('  Minimum likelihood:', inspectConfig.minLikelihood);
    console.log('  Include quotes:', inspectConfig.includeQuote);

    const limits = inspectConfig.limits;
    console.log('  Max findings per request:', limits.maxFindingsPerRequest);
  });
}

listInspectTemplates();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

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

/**
 * List DLP inspection configuration templates.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 */
function list_inspect_templates(string $callingProjectId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

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

    // Run request
    $listInspectTemplatesRequest = (new ListInspectTemplatesRequest())
        ->setParent($parent);
    $response = $dlp->listInspectTemplates($listInspectTemplatesRequest);

    // Print results
    $templates = $response->iterateAllElements();

    foreach ($templates as $template) {
        printf('Template %s' . PHP_EOL, $template->getName());
        printf('  Created: %s' . PHP_EOL, $template->getCreateTime()->getSeconds());
        printf('  Updated: %s' . PHP_EOL, $template->getUpdateTime()->getSeconds());
        printf('  Display Name: %s' . PHP_EOL, $template->getDisplayName());
        printf('  Description: %s' . PHP_EOL, $template->getDescription());

        $inspectConfig = $template->getInspectConfig();
        if ($inspectConfig === null) {
            print('  No inspect config.' . PHP_EOL);
        } else {
            printf('  Minimum likelihood: %s' . PHP_EOL, $inspectConfig->getMinLikelihood());
            printf('  Include quotes: %s' . PHP_EOL, $inspectConfig->getIncludeQuote());
            $limits = $inspectConfig->getLimits();
            printf('  Max findings per request: %s' . PHP_EOL, $limits->getMaxFindingsPerRequest());
        }
    }
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

import google.cloud.dlp


def list_inspect_templates(project: str) -> None:
    """Lists all Data Loss Prevention API inspect templates.
    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_inspect_templates(request={"parent": parent})

    for template in response:
        print(f"Template {template.name}:")
        if template.display_name:
            print(f"  Display Name: {template.display_name}")
        print(f"  Created: {template.create_time}")
        print(f"  Updated: {template.update_time}")

        config = template.inspect_config
        print(
            "  InfoTypes: {}".format(", ".join([it.name for it in config.info_types]))
        )
        print(f"  Minimum likelihood: {config.min_likelihood}")
        print(f"  Include quotes: {config.include_quote}")
        print(
            "  Max findings per request: {}".format(
                config.limits.max_findings_per_request
            )
        )

REST

使用下列其中一個 *.*.list 方法:

將檢查範本複製到 global 區域

  1. 前往 Google Cloud 控制台的 Sensitive Data Protection「Configuration」(設定) 頁面。

    前往「設定」

  2. 在工具列中,按一下專案選取器,然後選取要使用的檢查範本所在的專案。

  3. 依序點選「範本」分頁標籤和「檢查」子分頁標籤。

  4. 按一下要使用的範本 ID。

  5. 在「Inspection template details」(檢查範本詳細資料) 頁面中,按一下「Copy」(複製)。

  6. 在「Create template」(建立範本) 頁面的「Resource location」(資源位置) 清單中,選取「Global (any region)」(全域 (任何區域))。

  7. 點選「建立」。

範本會複製到 global 區域。

將檢查範本複製到其他專案

  1. 前往 Google Cloud 控制台的 Sensitive Data Protection「Configuration」(設定) 頁面。

    前往「設定」

  2. 在工具列中,按一下專案選取器,然後選取要使用的檢查範本所在的專案。

  3. 依序點選「範本」分頁標籤和「檢查」子分頁標籤。

  4. 按一下要使用的範本 ID。

  5. 在「Inspection template details」(檢查範本詳細資料) 頁面中,按一下「Copy」(複製)。

  6. 選取要複製檢查範本的專案。

    「Create template」(建立範本) 頁面會在您選取的專案中重新載入。

  7. 點選「建立」。

系統會在您選取的專案中建立範本。

刪除檢查範本

如何刪除檢查範本:

控制台

  1. 在 Google Cloud 控制台中,前往 Sensitive Data Protection 的「Configuration」(設定) 頁面。

    前往「設定」

  2. 選取要刪除的檢查範本所屬的專案。

  3. 按一下 [Templates] (範本) 分頁標籤。控制台會顯示目前專案的所有範本清單。

  4. 在「Actions」(動作) 欄中找到要刪除的範本,按一下「更多動作」選單 (垂直排列的三點圖示) ,然後點選「Delete」(刪除)。

您也可以在範本清單中,按一下要刪除的範本名稱,然後在範本的詳細資料頁面中,按一下 [Delete] (刪除)。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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


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

public class InspectTemplateDelete
{
    public static object Delete(string projectId, string templateName)
    {
        var client = DlpServiceClient.Create();

        var request = new DeleteInspectTemplateRequest
        {
            Name = templateName
        };

        client.DeleteInspectTemplate(request);
        Console.WriteLine($"Successfully deleted template {templateName}.");

        return templateName;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

import (
	"context"
	"fmt"
	"io"

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

// deleteInspectTemplate deletes the given template.
func deleteInspectTemplate(w io.Writer, templateID string) error {
	// projectID := "my-project-id"
	// templateID := "my-template"

	ctx := context.Background()

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

	req := &dlppb.DeleteInspectTemplateRequest{
		Name: templateID,
	}

	if err := client.DeleteInspectTemplate(ctx, req); err != nil {
		return fmt.Errorf("DeleteInspectTemplate: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted inspect template %v", templateID)
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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


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

class TemplatesDelete {

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

  // Delete an existing template
  public static void deleteInspectTemplate(String projectId, String templateId) throws IOException {
    // Construct the template name to be deleted
    String templateName = String.format("projects/%s/inspectTemplates/%s", projectId, templateId);

    // 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()) {

      // Create delete template request to be sent by the client
      DeleteInspectTemplateRequest request =
          DeleteInspectTemplateRequest.newBuilder().setName(templateName).build();

      // Send the request with the client
      dlpServiceClient.deleteInspectTemplate(request);
      System.out.printf("Deleted template: %s\n", templateName);
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「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 template to delete
// Parent project ID is automatically extracted from this parameter
// const templateName = 'projects/YOUR_PROJECT_ID/inspectTemplates/#####'
async function deleteInspectTemplate() {
  // Construct template-deletion request
  const request = {
    name: templateName,
  };

  // Run template-deletion request
  await dlp.deleteInspectTemplate(request);
  console.log(`Successfully deleted template ${templateName}.`);
}

deleteInspectTemplate();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

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

/**
 * Delete a DLP inspection configuration template.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 * @param string $templateId        The name of the template to delete
 */
function delete_inspect_template(
    string $callingProjectId,
    string $templateId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run template deletion request
    $templateName = "projects/$callingProjectId/locations/global/inspectTemplates/$templateId";
    $deleteInspectTemplateRequest = (new DeleteInspectTemplateRequest())
        ->setName($templateName);
    $dlp->deleteInspectTemplate($deleteInspectTemplateRequest);

    // Print results
    printf('Successfully deleted template %s' . PHP_EOL, $templateName);
}

Python

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱「Sensitive Data Protection 用戶端程式庫」。

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

import google.cloud.dlp


def delete_inspect_template(project: str, template_id: str) -> None:
    """Deletes a Data Loss Prevention API template.
    Args:
        project: The id of the Google Cloud project which owns the template.
        template_id: The id of the template 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 template id with the parent id.
    template_resource = f"{parent}/inspectTemplates/{template_id}"

    # Call the API.
    dlp.delete_inspect_template(request={"name": template_resource})

    print(f"Template {template_resource} successfully deleted.")

REST

使用下列其中一個 *.*.delete 方法:

在每個 *.*.delete 方法中,您需要加入要刪除的範本資源名稱。

後續步驟