機密データの保護の検査テンプレートの作成

このトピックでは、新しい検査テンプレートの作成方法を詳しく説明します。Google Cloud コンソールを使用して新しい検査テンプレートを作成する方法の簡単なチュートリアルについては、クイックスタート: 機密データの保護の検査テンプレートの作成をご覧ください。

テンプレートについて

テンプレートを使用して、機密データの保護で使用する構成情報を作成し、維持できます。テンプレートは、検査の目的や匿名化の方法などの構成情報をリクエストの実装から分離するのに役立ちます。テンプレートを使用することで構成を再利用でき、ユーザー間、データセット間での一貫性が保たれます。また、テンプレートを更新するたびに、そのテンプレートを使用するすべてのジョブトリガーが更新されます。

機密データの保護は、このトピックで説明する検査テンプレートと、機密データの保護匿名化テンプレートの作成で説明されている匿名化テンプレートをサポートしています。

Sensitive Data Protection のテンプレートの概念については、テンプレートをご覧ください。

新しい検査テンプレートの作成

コンソール

Google Cloud コンソールで、[テンプレートの作成] ページに移動します。

[テンプレートの作成] に移動

[テンプレートの作成 ページには次のセクションがあります。

テンプレートの定義

[テンプレートの定義] で、検査テンプレートの識別子を入力します。この ID を使って、ジョブの実行時やジョブトリガーの作成時などにテンプレートを参照します。文字、数字、ハイフンを使用できます。必要に応じて、よりわかりやすい表示名と説明を入力して、テンプレートの内容を覚えやすくすることもできます。

[リソース ロケーション] フィールドで、検査するデータが保存されているリージョンを選択します。作成した検査テンプレートもこのリージョンに保存されます。新しい検査テンプレートを任意のリージョンで使用するには、[グローバル(任意のリージョン)] を選択します。

検出を構成する

次に、infoType などのオプションを選択して、機密データの保護によるコンテンツ内の検出を構成します。

infoType 検出器は、特定の型の機密データを検出します。たとえば、機密データの保護の US_SOCIAL_SECURITY_NUMBER infoType 検出器では、米国社会保障番号が検出されます。組み込みの infoType 検出器に加えて、独自のカスタム infoType 検出器を作成できます。

[InfoTypes] セクションで、スキャンするデータ型に対応する infoType 検出器を選択します。このセクションは空白のままにしないことをおすすめします。空白のままにすると、機密データの保護がデフォルトの infoType セットでスキャンを実行します。これには、不要な infoType が含まれる場合があります。 それぞれの検出器の詳細については、InfoType 検出器リファレンスをご覧ください。

このセクションで説明されている組み込みとカスタムの infoType を管理する方法について詳しくは、Google Cloud コンソールを使用して infoType を管理するをご覧ください。

検査ルールセット

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 Sensitive Data Protection 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 Sensitive Data Protection 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.

信頼度のしきい値

機密データの保護で機密データの一致候補が検出されるたびに、可能性の値が「かなり低い」から「かなり高い」までの尺度で割り当てられます。ここで可能性の値を設定すると、機密データの保護は、その可能性の値以上のデータの一致のみを検出するように指示されます。

「可能性あり」はデフォルト値で、ほとんどの用途に十分対応できます。検出される一致が常に、あまりに広範に及ぶ場合は、スライダーを右に動かしてください。一致が少なすぎる場合は、スライダーを左に動かしてください。

設定が完了したら、[作成] をクリックしてテンプレートを作成します。テンプレートの要約情報のページが表示されます。

機密データの保護のメインページに戻るには、Google Cloud コンソールの [戻る] 矢印をクリックします。

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

Go

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。


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

PHP

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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. projects.inspectTemplates または organizations.inspectTemplates リソースの create メソッドを呼び出すか POST し、そのリクエストに表示名、説明、作成した InspectConfig オブジェクトを入れた InspectTemplate オブジェクトを含めます。

返された InspectTemplate はすぐに使用できます。その name を使用して、他の呼び出しやジョブでこのテンプレートを参照できます。既存のテンプレートを一覧表示するには、*.inspectTemplates.list メソッドを呼び出します。特定のテンプレートを表示するには、*.inspectTemplates.get メソッドを呼び出します。作成できるテンプレート数の上限は 1,000 個です。

機密データの保護を使用して、機密コンテンツに関してテキスト、画像、構造化コンテンツを過去に検査したことがある場合、InspectConfig オブジェクトはすでに作成されています。もう 1 つの手順を行うだけで、これを 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 Explorer を使用すれば、これをすぐに試すことができます。JSON を使用して DLP API にリクエストを送信する方法については、JSON クイックスタートをご覧ください。

検査テンプレートの使用

新しい検査テンプレートを作成したら、それを新しい検査ジョブまたはジョブトリガーの作成時に使用できます。そのテンプレートを更新するたびに、そのテンプレートを使用するすべてのジョブトリガーで更新されます。コードサンプルなどの詳細については、以下をご覧ください。

コンソール

新しいテンプレートの使用を開始するには、クイックスタート: 機密データの保護の検査テンプレートの作成に記載されている手順に従います。

  • [検出の構成] の [テンプレート] セクションで、[テンプレート名] フィールドをクリックし、作成したテンプレートを選択します。

コンテンツのスキャン方法の詳細については、機密データの保護の検査ジョブの作成とスケジューリングの「検出の構成」セクションをご覧ください。

REST

次のような inspectTemplateName が使用可能であればどこでも、テンプレートの作成時に指定したテンプレート ID を使用できます。

  • projects.content.inspect: テンプレートを構成として使用して、コンテンツ内の潜在的な機密データを匿名化します。
  • projects.content.deidentify: テンプレートを構成として使用して、コンテンツ内の機密データを検出して匿名化します。このメソッドでは、検査テンプレートと匿名化テンプレートの両方を使用することに注意してください。
  • InspectJobConfig オブジェクト内の projects.dlpJobs.create: 構成としてテンプレートを含む検査ジョブを作成します。

検査テンプレートの一覧表示

現在のプロジェクトまたは組織で作成されたすべての検査テンプレートを一覧表示する手順は次のとおりです。

コンソール

  1. Google Cloud コンソールで、機密データの保護の [構成] ページに移動します。

    [構成] に移動

  2. 検査テンプレートを含むプロジェクトを選択します。

  3. [テンプレート] タブをクリックします。

現在のプロジェクトにあるすべての検査テンプレートが一覧表示されます。

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

Go

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。


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

PHP

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 コンソールで、機密データの保護の [構成] ページに移動します。

    [構成] に移動

  2. ツールバーでプロジェクト セレクタをクリックし、使用する検査テンプレートを含むプロジェクトを選択します。

  3. [テンプレート] タブをクリックし、[検査] サブタブをクリックします。

  4. 使用するテンプレートの ID をクリックします。

  5. [検査テンプレートの詳細] ページで、[コピー] をクリックします。

  6. [テンプレートの作成] ページの [リソース ロケーション] リストで、[グローバル(任意のリージョン)] を選択します。

  7. [作成] をクリックします。

テンプレートが global リージョンにコピーされます。

検査テンプレートを別のプロジェクトにコピーする

  1. Google Cloud コンソールで、機密データの保護の [構成] ページに移動します。

    [構成] に移動

  2. ツールバーでプロジェクト セレクタをクリックし、使用する検査テンプレートを含むプロジェクトを選択します。

  3. [テンプレート] タブをクリックし、[検査] サブタブをクリックします。

  4. 使用するテンプレートの ID をクリックします。

  5. [検査テンプレートの詳細] ページで、[コピー] をクリックします。

  6. 検査テンプレートのコピー先となるプロジェクトを選択します。

    選択したプロジェクトで [テンプレートの作成] ページが再読み込みされます。

  7. [作成] をクリックします。

選択したプロジェクトでテンプレートが作成されます。

検査テンプレートの削除

検査テンプレートを削除する手順は次のとおりです。

コンソール

  1. Google Cloud コンソールで、機密データの保護の [構成] ページに移動します。

    [構成] に移動

  2. 削除する検査テンプレートを含むプロジェクトを選択します。

  3. [テンプレート] タブをクリックします。現在のプロジェクトにあるすべてのテンプレートが一覧表示されます。

  4. 削除するテンプレートの [操作] 列で、[その他の操作] メニュー(縦に並んだ 3 つの点) をクリックし、[削除] をクリックします。

または、テンプレートの一覧から削除対象のテンプレートの名前をクリックし、テンプレートの詳細ページで [削除] をクリックします。

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

Go

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。


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

PHP

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

機密データの保護用のクライアント ライブラリをインストールして使用する方法については、機密データの保護のクライアント ライブラリをご覧ください。

機密データの保護のために認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 メソッドには、削除するテンプレートのリソース名を含めます。