创建敏感数据保护检查模板

本主题详细介绍如何创建新的检查模板。如需快速浏览如何使用 Google Cloud 控制台创建新的检查模板,请参阅快速入门:创建 Sensitive Data Protection 检查模板

模板简介

您可以使用模板创建和保留配置信息以在 Sensitive Data Protection 中使用。模板可用于分离配置信息(如检查的内容和对内容进行去标识化的方式)与请求的实现。模板提供了一种方法,让您能够重复使用配置并在用户和数据集之间实现一致性。此外,每次您更新模板时,系统都会为使用该模板的任何作业触发器更新该模板。

Sensitive Data Protection 支持检查模板,我们会在 以及去标识化模板(我们将在本课程中 创建敏感数据保护去标识化 模板

如需了解敏感数据保护中模板的相关概念,请参阅 模板

创建新的检查模板

控制台

在 Google Cloud 控制台中,前往创建模板页面。

前往“创建模板”

创建模板页面包含以下部分:

定义模板

定义模板下,输入检查模板的标识符。在运行作业及创建作业触发器等操作时您可以借此引用模板。标识符可使用字母、数字和连字符。如果需要,您还可以输入更便于理解的显示名以及说明,以便更好地记住模板的用途。

资源位置字段中,选择要检查的数据的存储区域。您创建的检查模板也会存储在此区域。如果您希望能够在任何区域使用新检查模板,请选择全球(任何区域)

配置检测

接下来,您可以配置 Sensitive Data Protection 在内容中检测的内容,方法是通过以下方式 选择 infoType 和其他选项。

InfoType 检测器会查找特定类型的敏感数据。例如,敏感数据保护 US_SOCIAL_SECURITY_NUMBER infoType 检测器会查找美国社会保障号。除了内置的 infoType 检测器之外,您还可以自行创建自定义 infoType 检测器。

InfoTypes 部分中,选择与数据对应的 infoType 检测器 您要扫描的类型。我们不建议您将此部分留空。这样一来,敏感数据保护就会使用一组默认的 infoType 扫描您的数据,其中可能包含您不需要的 infoType。如需详细了解每种检测器,请参阅 InfoType 检测器参考文档

如需详细了解如何在 Google Cloud 控制台中管理内置和自定义 infoType,请访问 本部分请参阅通过 Google Cloud 控制台管理 infoType

检查规则集

通过检查规则集,您可以使用 上下文规则。检查规则分为两种:

  • 排除规则:有助于排除误报或不需要的发现结果。
  • 热词规则 以帮助检测其他发现结果。

如需添加新规则集,请先在 InfoTypes 部分。这些是规则集将修改的 infoType 检测器。然后,执行以下操作:

  1. 点击 Choose infoTypes 字段。您之前指定的 infoType 会显示在该字段下方的菜单中,如下所示:
  2. DLP 界面的检查规则集配置的屏幕截图。
  3. 从菜单中选择一个 infoType,然后点击添加规则。系统会显示一个菜单 热词规则排除规则两个选项。

对于热词规则,请选择热词规则。然后,执行以下操作:

  1. 热词字段中,输入表明 Sensitive Data Protection 的正则表达式 。
  2. 热词接近度菜单中,选择是在所选 infoType 之前还是之后找到您输入的热词。
  3. 热词与 infoType 的距离中,输入大致的字符数 。
  4. 置信度调整中,选择是否将与固定的 可能性级别,也可以提高或降低 指定一定的概率水平。

对于排除规则,请选择排除规则。然后,执行以下操作:

  1. 排除字段中,输入敏感数据保护功能应查找的正则表达式 (regex)。
  2. 匹配类型菜单中,选择以下选项之一:
    • 完全匹配:发现内容必须与正则表达式完全匹配。
    • 部分匹配:相应发现结果的子字符串可以与正则表达式匹配。
    • 反向匹配:发现结果与正则表达式不匹配。

您可以添加其他热词或排除规则和规则集,以进一步优化扫描结果。

置信度阈值

每当 Sensitive Data Protection 检测到敏感数据的潜在匹配项时, 会为其分配一个可能性值,范围为“非常不可能” 设置为“很有可能”。在此处设置可能性值时,您将指示 Sensitive Data Protection,以便仅匹配与相应可能性对应的数据 值或更高值。

默认值“可能”(Possible) 足以满足大多数情况。如果您经常获得太过宽泛的匹配项,请调高滑块的值。如果匹配项太少,请调低滑块的值。

完成后,请点击创建以创建模板。您将看到模板的汇总信息页面。

如需返回“敏感数据保护”主页面,请点击以下位置中的返回箭头: Google Cloud 控制台

C#

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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.inspectTemplatesorganizations.inspectTemplates 资源的 create 方法,在请求中包含一个带显示名、说明和该 InspectConfig 对象的 InspectTemplate 对象。

返回的 InspectTemplate 立即可供使用。您可以通过其 name 在其他调用或作业中引用它。您可以通过调用 *.inspectTemplates.list 方法列出现有模板。如需查看特定模板,请调用 *.inspectTemplates.get 方法。请注意,可创建的模板数量上限为 1000。

如果您曾使用 Sensitive Data Protection 检查文本、图片或结构化内容是否包含敏感内容,则表示您已创建 InspectConfig 对象。再执行一步,即可将其转换为 InspectTemplate 对象。

下面的 JSON 示例展示了您可以向 projects.inspectTemplates.create 方法发送哪些内容。此 JSON 会创建一个具有给定显示名和说明的新模板,并依据 infoType PHONE_NUMBERUS_TOLLFREE_PHONE_NUMBER 扫描匹配项。其结果中将包含最多 100 个可能性至少为 POSSIBLE 的匹配项,以及每个匹配项的一小段上下文。

JSON 输入:

POST https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/inspectTemplates?key={YOUR_API_KEY}

{
  "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 检查模板中的说明操作,但下面这个步骤有所不同:

  • 配置检测 > 模板部分中,点击模板名称字段,然后选择刚创建的模板。

如需详细了解如何扫描内容,请参阅创建和安排敏感数据保护检查作业并特别注意“配置检测”这一节。

REST

您可以在任何接受 inspectTemplateName 的位置使用您在创建模板时指定的模板标识符,例如:

列出检查模板

如需列出已在当前项目或组织中创建的所有检查模板,请执行以下操作:

控制台

  1. 在 Google Cloud 控制台中,前往配置页面 Sensitive Data Protection。

    前往“配置”

  2. 选择包含检查模板的项目。

  3. 点击模板标签页。

Console 中显示当前项目的所有检查模板的列表。

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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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” 配置页面。

    前往“配置”

  2. 在工具栏上,点击项目选择器,然后选择包含您要使用的检查模板的项目。

  3. 点击模板标签页,然后点击检查子标签页。

  4. 点击要使用的模板的 ID。

  5. 检查模板详情页面上,点击复制

  6. 创建模板页面的资源位置列表中,选择 Global (any region)

  7. 点击创建

该模板会复制到 global 区域。

将检查模板复制到其他项目

  1. 在 Google Cloud 控制台中,前往“Sensitive Data Protection” 配置页面。

    前往“配置”

  2. 在工具栏中,点击项目选择器,然后选择需要 包含您要使用的检查模板。

  3. 点击模板标签页,然后点击检查子标签页。

  4. 点击要使用的模板的 ID。

  5. 检查模板详情页面上,点击复制

  6. 选择您要创建的项目 您要将检查模板复制到哪个目标文件夹

    创建模板页面会在您选择的项目中重新加载。

  7. 点击创建

模板会在您选择的项目中创建。

删除检查模板

如需删除检查模板,请执行以下操作:

控制台

  1. 在 Google Cloud 控制台中,前往“敏感数据保护”的配置页面。

    前往“配置”

  2. 选择包含您要删除的检查模板的项目。

  3. 点击模板标签页。Console 会显示当前项目的所有模板的列表。

  4. 在要删除的模板的操作列中,点击更多操作菜单(显示为纵向排列的三个点),然后点击删除

或者,从模板列表中,点击要删除的模板的名称。在模板的详细信息页面上,点击删除

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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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 方法,均需添加要删除的模板的资源名称。