Cloud DLP 검사 템플릿 만들기

이 주제에서는 새 검사 템플릿을 만드는 방법을 자세하게 설명합니다. Cloud Data Loss Prevention(DLP) UI를 사용하여 새 검사 템플릿을 만드는 방법을 빠르게 둘러보려면 빠른 시작: Cloud DLP 검사 템플릿 만들기를 참조하세요.

템플릿 정보

템플릿을 사용하여 Cloud DLP에서 사용할 구성 정보를 만들고 유지할 수 있습니다. 템플릿은 검사 대상 및 익명화 방법과 같은 구성 정보를 요청 구현에서 분리하는 데 유용하며, 구성을 재사용할 수 있는 방법을 제공하고 사용자와 데이터세트 전반에서 일관성을 유지할 수 있게 해줍니다. 또한 템플릿을 업데이트할 때마다 템플릿을 사용하는 모든 작업 트리거에 대해 업데이트됩니다.

Cloud DLP는 검사 템플릿과 익명화 템플릿을 지원합니다. 검사 템플릿은 이 주제에서 다루며 익명화 템플릿은 Cloud DLP 익명화 템플릿 만들기에서 다룹니다.

Cloud DLP 템플릿의 개념 정보는 템플릿을 참조하세요.

새 검사 템플릿 만들기

새 Cloud DLP 템플릿을 만드는 방법은 다음과 같습니다.

Console

  1. Cloud Console에서 Cloud DLP를 엽니다.

    Cloud DLP UI로 이동

  2. 만들기 메뉴에서 템플릿을 선택합니다.

    또는 다음 버튼을 클릭합니다.

    새 템플릿 만들기

템플릿 만들기 페이지는 다음 섹션으로 구성되어 있습니다.

템플릿 정의

템플릿 정의에서 검사 템플릿의 식별자를 입력합니다. 그러면 작업을 실행하거나 작업 트리거를 만들 때 이 이름으로 템플릿을 참조할 수 있습니다. 문자, 숫자, 하이픈을 사용할 수 있습니다. 필요한 경우 템플릿 기능을 기억하는 데 도움이 되도록 설명과 함께 사용자 친화적인 표시 이름을 입력할 수도 있습니다.

감지 구성

다음으로 infoType 및 기타 옵션을 선택하여 Cloud DLP가 콘텐츠에서 감지하는 항목을 구성합니다.

InfoType 감지기는 특정 유형의 민감한 정보를 찾습니다. 예들 들어 Cloud DLP US_SOCIAL_SECURITY_NUMBER infoType 감지기는 미국 사회보장 번호를 찾습니다. 기본 제공 infoType 감지기 외에 고유 한 커스텀 infoType 감지기도 만들 수 있습니다.

InfoTypes에서 스캔할 데이터 유형에 해당하는 infoType 감지기를 선택합니다. 또한 모든 기본 infoType을 스캔하려면 이 필드를 비워둘 수 있습니다. 각 감지기에 대한 자세한 내용은 InfoType 감지기 참조를 확인하세요.

또한 커스텀 infoType 섹션에 커스텀 infoType 감지기를 추가하고 검사 규칙 세트 섹션에서 기본 제공 infoType 감지기와 커스텀 infoType 감지기를 모두 맞춤설정할 수 있습니다.

커스텀 infoType

To add a custom infoType detector:

  1. Click Add custom infoType.
  2. Choose the type of custom infoType detector you want to create:
    • Words or phrases: Matches on one or more words or phrases that you enter into the field. Use this custom infoType when you have just a few words or phrases to search for. Give your custom infoType a name, and then, under List of words or phrases, type the word or phrase you want Cloud DLP to match on. To search on multiple words or phrases, press Enter after each one. For more information, see Creating a regular custom dictionary detector.
    • Dictionary path: Searches your content for items in a list of words and phrases. The list is stored in a text file in Cloud Storage. Use this custom infoType when you have anywhere from a few to several hundred thousand words or phrases to search for. This method is also useful if your list contains sensitive elements and you don't want to store them inside of a job or template. Give your custom infoType a name, and then, under Dictionary location, enter or browse to the Cloud Storage path where the dictionary file is stored. For more information, see Creating a regular custom dictionary detector.
    • Regex: Matches content based on a regular expression. Give your custom infoType a name, and then, in the Regex field, enter a regex pattern to match words and phrases. See the supported regex syntax.
    • Stored infoType: This option adds a stored custom dictionary detector, which is a kind of dictionary detector that is built from either a large text file stored in Cloud Storage or a single column of a BigQuery table. Use this kind of custom infoType when you have anywhere from several hundred thousand to tens of millions of words or phrases to search for. Be aware that this is the only option in this menu for which you must have already created the stored infoType to use it. Give your custom infoType a name (different from the name you gave the stored infoType), and then, in the Stored infoType field, enter the name of the stored infoType. For more information about creating stored custom dictionaries, see Creating a stored custom dictionary detector.

Click Add custom infoType again to add additional custom infoType detectors.

검사 규칙 세트

Inspection rulesets allow you to customize both built-in and custom infoType detectors using context rules. The two types of inspection rules are:

To add a new ruleset, first specify one or more built-in or custom infoType detectors in the InfoTypes section. These are the infoType detectors that your rulesets will be modifying. Then, do the following:

  1. Click in the Choose infoTypes field. The infoType or infoTypes you specified previously appear below the field in a menu, as shown here:
  2. Screenshot of the DLP UI's inspection rulesets configuration.
  3. Choose an infoType from the menu, and then click Add rule. A menu appears with the two options Hotword rule and Exclusion rule.

For hotword rules, choose Hotword rules. Then, do the following:

  1. In the Hotword field, enter a regular expression that Cloud DLP should look for.
  2. From the Hotword proximity menu, choose whether the hotword you entered is found before or after the chosen infoType.
  3. In Hotword distance from infoType, enter the approximate number of characters between the hotword and the chosen infoType.
  4. In Confidence level adjustment, choose whether to assign matches a fixed likelihood level, or to increase or decrease the default likelihood level by a certain amount.

For exclusion rules, choose Exclusion rules. Then, do the following:

  1. In the Exclude field, enter a regular expression (regex) that Cloud DLP should look for.
  2. From the Matching type menu, choose one of the following:
    • Full match: The finding must completely match the regex.
    • Partial match: A substring of the finding can match the regex.
    • Inverse match: The finding doesn't match the regex.

You can add additional hotword or exclusion rules and rulesets to further refine your scan results.

신뢰도 기준

Cloud DLP가 민감한 정보의 잠재적인 일치 항목을 감지할 때마다 일치 항목에 'Very unlikely'에서 'Very likely' 범위의 가능성 값을 할당합니다. 여기서 가능성 값을 설정하면 Cloud DLP는 이 가능성 값 이상에 해당하는 데이터만 비교하게 됩니다.

기본값인 '가능성 있음'은 대부분의 용도에 적합합니다. 일반적으로 결과가 너무 많이 검색되면 슬라이더를 위로 이동합니다. 일치 항목 결과가 너무 적으면 슬라이더를 아래로 이동합니다.

완료되면 만들기를 클릭하여 템플릿을 만듭니다. 템플릿의 요약 정보 페이지가 표시됩니다.

기본 Cloud DLP 페이지로 돌아가려면 Cloud Console에서 뒤로 화살표를 클릭합니다.

프로토콜

검사 템플릿은 재사용 가능한 검사 구성에 일부 메타데이터를 더한 것일 뿐입니다. API 용어에서 InspectTemplate 객체는 사실상 표시 이름 및 설명과 같은 몇 가지 추가 메타데이터 필드가 포함된 InspectConfig 객체입니다. 따라서 새 검사 템플릿을 만들기 위한 기본 단계는 다음과 같습니다.

  1. InspectConfig 객체로 시작합니다.
  2. projects.inspectTemplates 또는 organizations.inspectTemplates 리소스의 create 메서드를 호출하거나 게시하며, 이때 요청에 표시 이름, 설명, InspectConfig 객체가 있는 InspectTemplate 객체를 포함합니다.

반환되는 InspectTemplate은 즉시 사용할 수 있습니다. 다른 호출 또는 작업에서 name으로 참조할 수 있습니다. *.inspectTemplates.list 메서드를 호출하여 기존 템플릿을 나열할 수 있습니다. 특정 템플릿을 보려면 *.inspectTemplates.get 메서드를 호출합니다. 만들 수 있는 템플릿 수의 한도는 1000개입니다.

Cloud DLP를 사용하여 텍스트, 이미지, 구조화된 콘텐츠에서 민감한 콘텐츠를 검사한 경험이 있다면 이미 InspectConfig 객체를 만든 것입니다. 한 가지 부가적인 단계로 이 객체를 InspectTemplate 객체로 변환합니다.

다음 JSON은 projects.inspectTemplates.create 메서드에 전송할 수 있는 항목의 예시입니다. 이 JSON은 주어진 표시 이름과 설명으로 새 템플릿을 만들고 infoType PHONE_NUMBERUS_TOLLFREE_PHONE_NUMBER의 일치 항목을 스캔합니다. 결과에 가능성이 POSSIBLE 이상인 일치 항목을 최대 100개 포함하며, 각각의 맥락도 일부분 포함합니다.

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

이를 빠르게 시도하려면 아래에 포함된 API 탐색기를 사용할 수 있습니다. JSON을 사용하여 Cloud DLP API로 요청을 전송하는 방법에 대한 일반적인 정보는 JSON 빠른 시작을 참조하세요.

자바


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

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

Python

def create_inspect_template(
    project,
    info_types,
    template_id=None,
    display_name=None,
    min_likelihood=None,
    max_findings=None,
    include_quote=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.
    """

    # Import the client library
    import google.cloud.dlp

    # 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("Successfully created template {}".format(response.name))

Go

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2"
)

// 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: %v", err)
	}

	// 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: %v", err)
	}
	// Print the result.
	fmt.Fprintf(w, "Successfully created inspect template: %v", resp.GetName())
	return nil
}

PHP

/**
 * Create a new DLP inspection configuration template.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectTemplate;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;

/** Uncomment and populate these variables in your code */
// $callingProjectId = 'The project ID to run the API call under';
// $templateId = 'The name of the template to be created';
// $displayName = ''; // (Optional) The human-readable name to give the template
// $description = ''; // (Optional) A description for the trigger to be created
// $maxFindings = 0;  // (Optional) The maximum number of findings to report per request (0 = server maximum)

// 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";
$template = $dlp->createInspectTemplate($parent, $inspectTemplate, [
    'templateId' => $templateId
]);

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

C#


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

검사 템플릿 사용

새 검사 템플릿을 만든 후에는 새 검사 작업 또는 작업 트리거를 만들 때 이 템플릿을 사용할 수 있습니다. 또한 템플릿을 업데이트할 때마다 템플릿을 사용하는 모든 작업 트리거에 대해 업데이트됩니다. 코드 샘플을 포함한 자세한 내용은 다음을 참조하세요.

Console

새 템플릿을 사용하여 빠르게 시작하려면 다음 변경사항과 함께 빠른 시작: Cloud DLP 검사 템플릿 만들기에 제공된 안내를 따르세요.

  • 감지 구성 > 템플릿 섹션에서 템플릿 이름 필드를 클릭하고 방금 만든 템플릿을 선택합니다.

콘텐츠 스캔 방법에 대해 더 심층적으로 알아보려면 '감지 구성' 섹션에 특히 주의하여 Cloud DLP 검사 작업 만들기 및 예약을 참조하세요.

프로토콜

다음과 같이 inspectTemplateName이 허용되는 모든 위치에서 템플릿을 만들 때 지정한 템플릿 식별자를 사용할 수 있습니다.

  • projects.content.inspect: 템플릿을 구성으로 사용하여 콘텐츠의 잠재적인 민감한 정보를 익명화합니다.
  • projects.content.deidentify: 템플릿을 구성으로 사용하여 콘텐츠의 잠재적인 민감한 정보를 찾아서 익명화합니다. 이 메서드는 검사 템플릿과 익명화 템플릿을 모두 사용합니다.
  • projects.dlpJobs.create(InspectJobConfig 객체): 템플릿을 구성으로 포함하는 검사 작업을 만듭니다.

검사 템플릿 나열

현재 프로젝트 또는 조직에서 만든 모든 검사 템플릿을 나열하는 방법은 다음과 같습니다.

Console

  1. Cloud Console에서 Cloud DLP를 엽니다.

    Cloud DLP UI로 이동

  2. 템플릿 탭을 클릭합니다.

콘솔에 현재 프로젝트의 모든 검사 템플릿 목록이 표시됩니다.

프로토콜

*.*.list 메서드 중 하나를 사용합니다.

자바


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

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

Python

def list_inspect_templates(project):
    """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.
    """

    # Import the client library
    import google.cloud.dlp

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

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

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

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

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

Go

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

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

// 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: %v", err)
	}

	// 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: %v", err)
		}
		fmt.Fprintf(w, "Inspect template %v\n", t.GetName())
		c, err := ptypes.Timestamp(t.GetCreateTime())
		if err != nil {
			return fmt.Errorf("CreateTime Timestamp: %v", err)
		}
		fmt.Fprintf(w, "  Created: %v\n", c.Format(time.RFC1123))
		u, err := ptypes.Timestamp(t.GetUpdateTime())
		if err != nil {
			return fmt.Errorf("UpdateTime Timestamp: %v", err)
		}
		fmt.Fprintf(w, "  Updated: %v\n", u.Format(time.RFC1123))
		fmt.Fprintf(w, "  Display Name: %q\n", t.GetDisplayName())
		fmt.Fprintf(w, "  Description: %q\n", t.GetDescription())
	}

	return nil
}

PHP

/**
 * List DLP inspection configuration templates.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;

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

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

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

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

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

C#


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

검사 템플릿 삭제

검사 템플릿을 삭제하는 방법은 다음과 같습니다.

Console

  1. Cloud Console에서 Cloud DLP를 엽니다.

    Cloud DLP UI로 이동

  2. 구성 탭을 클릭한 다음 템플릿 탭을 클릭합니다. 콘솔에 현재 프로젝트의 모든 템플릿 목록이 표시됩니다.

  3. 삭제할 템플릿의 작업 열에서 작업 더보기 메뉴(세로로 정렬된 세 개의 점으로 표시됨) 를 클릭한 다음 삭제를 클릭합니다.

또는 템플릿 목록에서 삭제할 템플릿 이름을 클릭합니다. 템플릿의 세부정보 페이지에서 삭제를 클릭합니다.

프로토콜

*.*.delete 메서드 중 하나를 사용합니다.

*.*.delete 메서드에는 삭제할 템플릿의 리소스 이름을 포함합니다.

자바


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

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

Python

def delete_inspect_template(project, template_id):
    """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.
    """

    # Import the client library
    import google.cloud.dlp

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

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

    # Combine the template id with the parent id.
    template_resource = "{}/inspectTemplates/{}".format(parent, template_id)

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

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

Go

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2"
)

// 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: %v", err)
	}

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

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

PHP

/**
 * Delete a DLP inspection configuration template.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;

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

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

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

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

C#


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