建立 Cloud DLP 去識別化範本

您可以使用「範本」建立及保留設定資訊,以便與 Cloud Data Loss Prevention (DLP) 搭配使用。範本很適合用於將檢查內容和去識別化方式等設定與要求的實作分離,範本不僅可以讓您重複使用設定,也能保持使用者和資料集之間的一致性。

Cloud DLP 支援以下兩種類型的範本:

  • 去識別化範本:用於儲存去識別化工作設定資訊的範本,包括 infoType 和記錄 (結構化資料集) 轉換。
  • 檢查範本:用於保留檢查掃描工作設定資訊的範本,包括要使用的預先定義或自訂偵測工具。如要進一步瞭解如何建立範本,請參閱建立 Cloud DLP 檢查範本一文。

如要瞭解 Cloud DLP 範本的概念資訊,請參閱範本一文。

本主題的其餘部分會說明如何建立去識別化範本,以與 Cloud DLP 搭配使用。

建立去識別化範本

請注意,去識別化範本只是可重複使用的去識別化設定,再加上一些中繼資料而已。就 API 而言,DeidentifyTemplate 物件其實是 DeidentifyConfig 物件,只是包括多一點的中繼資料欄位,如顯示名稱和說明。所以,建立新的去識別化範本的基本步驟包括:

  1. DeidentifyConfig 物件開始。
  2. 呼叫或透過 POST 使用 projects.deidentifyTemplatesorganizations.deidentifyTemplates 資源的 create 方法,在您的要求中加入含有顯示名稱、說明和 DeidentifyConfig 物件的 DeidentifyTemplate 物件。

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

如果您在使用 Cloud DLP 將文字、圖片或結構化內容中的機密資料去識別化方面已有一些經驗,那麼您已經建立 DeidentifyConfig 物件,接下來只要再一個步驟就可以將這個物件轉成 DeidentifyTemplate 物件。

REST 範本

以下 JSON 是您可以傳送到 projects.deidentifyTemplates.create 方法的內容範例 (請在 APIs Explorer 中親自操作一下)。這個 JSON 會建立一個含有指定顯示名稱和說明的新範本,然後會比對 infoTypes EMAIL_ADDRESSLAST_NAME 掃描相符項目。當它發現與這些 infoTypes 相符的內容時,就會使用星號 (*) 字元遮蔽前三個字元。

JSON 輸入:

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

{
  "deidentifyTemplate":{
    "displayName":"Email last name mask",
    "description":"De-identifies emails and last names with a series of asterisks.",
    "deidentifyConfig":{
      "infoTypeTransformations":{
        "transformations":[
          {
            "infoTypes":[
              {
                "name":"LAST_NAME"
              }
            ],
            "primitiveTransformation":{
              "replaceWithInfoTypeConfig":{

              }
            }
          },
          {
            "infoTypes":[
              {
                "name":"EMAIL_ADDRESS"
              }
            ],
            "primitiveTransformation":{
              "characterMaskConfig":{
                "charactersToIgnore":[
                  {
                    "charactersToSkip":"@"
                  }
                ],
                "maskingCharacter":"*"
              }
            }
          }
        ]
      }
    }
  }
}

JSON 輸出:

{
  "name":"projects/[PROJECT_ID]/deidentifyTemplates/[JOB-ID]",
  "displayName":"Email last name mask",
  "description":"De-identifies emails and last names with a series of asterisks.",
  "createTime":"2018-11-30T07:17:59.536022Z",
  "updateTime":"2018-11-30T07:17:59.536022Z",
  "deidentifyConfig":{
    "infoTypeTransformations":{
      "transformations":[
        {
          "infoTypes":[
            {
              "name":"LAST_NAME"
            }
          ],
          "primitiveTransformation":{
            "replaceWithInfoTypeConfig":{

            }
          }
        },
        {
          "infoTypes":[
            {
              "name":"EMAIL_ADDRESS"
            }
          ],
          "primitiveTransformation":{
            "characterMaskConfig":{
              "maskingCharacter":"*",
              "charactersToIgnore":[
                {
                  "charactersToSkip":"@"
                }
              ]
            }
          }
        }
      ]
    }
  }
}

使用去識別化範本

建立新範本之後,即可將範本的 name 識別項用於接受 deidentifyTemplateName 的任何位置,例如:

  • projects.content.deidentify:使用範本做為設定,將內容中可能有的機密資料去識別化。請注意,這個方法可使用檢查範本或去識別化範本。

列出去識別化範本

如要列出已建立的所有去識別化範本,請使用 *.*.list 方法之一:

程式碼範例

以下是幾種不同程式語言的範例程式碼,示範如何使用 Cloud DLP 列出檢查範本。這個程序與列出去識別化範本的程序相同。

Java

/**
 * List DLP inspection templates created in a given project
 *
 * @param projectId Google Cloud Project ID
 */
private static void listInspectTemplates(String projectId) {

  try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

    ListInspectTemplatesRequest request =
        ListInspectTemplatesRequest.newBuilder()
            .setParent(ProjectName.of(projectId).toString())
            .setPageSize(1)
            .build();

    ListInspectTemplatesPagedResponse response = dlpServiceClient.listInspectTemplates(request);
    ListInspectTemplatesPage page = response.getPage();
    ListInspectTemplatesResponse templatesResponse = page.getResponse();

    for (InspectTemplate template : templatesResponse.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());
      }
    }
  } catch (Exception e) {
    System.out.printf("Error creating template: %s", e.getMessage());
  }
}

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 callingProjectId = process.env.GCLOUD_PROJECT;

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

// Construct template-listing request
const request = {
  parent: dlp.projectPath(callingProjectId),
};

try {
  // 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);
  });
} catch (err) {
  console.log(`Error in listInspectTemplates: ${err.message || err}`);
}

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.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = dlp.project_path(project)

    # Call the API.
    response = dlp.list_inspect_templates(parent)

    # Define a helper function to convert the API's "seconds since the epoch"
    # time format into a human-readable string.
    def human_readable_time(timestamp):
        return str(time.localtime(timestamp.seconds))

    for template in response:
        print('Template {}:'.format(template.name))
        if template.display_name:
            print('  Display Name: {}'.format(template.display_name))
        print('  Created: {}'.format(
            human_readable_time(template.create_time)))
        print('  Updated: {}'.format(
            human_readable_time(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

// listInspectTemplates lists the inspect templates in the project.
func listInspectTemplates(w io.Writer, client *dlp.Client, project string) {
	// Create a configured request.
	req := &dlppb.ListInspectTemplatesRequest{
		Parent: "projects/" + project,
	}
	// Send the request and iterate over the results.
	it := client.ListInspectTemplates(context.Background(), req)
	for {
		t, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatalf("error getting inspect templates: %v", err)
		}
		c := t.GetCreateTime()
		u := t.GetUpdateTime()
		fmt.Fprintf(w, "Inspect template %v\n", t.GetName())
		fmt.Fprintf(w, "  Created: %v\n", time.Unix(c.GetSeconds(), int64(c.GetNanos())).Format(time.RFC1123))
		fmt.Fprintf(w, "  Updated: %v\n", time.Unix(u.GetSeconds(), int64(u.GetNanos())).Format(time.RFC1123))
		fmt.Fprintf(w, "  Display Name: %q\n", t.GetDisplayName())
		fmt.Fprintf(w, "  Description: %q\n", t.GetDescription())
	}
}

PHP

use Google\Cloud\Dlp\V2\DlpServiceClient;

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

    $parent = $dlp->projectName($callingProjectId);

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

public static object ListInspectTemplate(string projectId)
{
    DlpServiceClient client = DlpServiceClient.Create();

    var response = client.ListInspectTemplates(
        new ListInspectTemplatesRequest
        {
            Parent = $"projects/{projectId}",
        }
    );
    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}");
    }

    return null;
}

刪除去識別化範本

如要刪除特定的去識別化範本,請使用 *.*.delete 方法之一:

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

程式碼範例

以下是幾種不同程式語言的範例程式碼,示範如何使用 Cloud DLP 刪除檢查範本。這個程序與列出去識別化範本的程序相同。

Java

/**
 * Delete the DLP inspection configuration template with the specified name.
 *
 * @param projectId Google Cloud Project ID
 * @param templateId Template ID to be deleted
 */
private static void deleteInspectTemplate(String projectId, String templateId) {

  // construct the template name to be deleted
  String templateName = String.format("projects/%s/inspectTemplates/%s", projectId, templateId);
  // instantiate the client
  try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
    // create delete template request
    DeleteInspectTemplateRequest request =
        DeleteInspectTemplateRequest.newBuilder().setName(templateName).build();

    dlpServiceClient.deleteInspectTemplate(request);
    System.out.printf("Deleted template: %s\n", templateName);
  } catch (Exception e) {
    System.err.printf("Error deleting 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 name of the template to delete
// Parent project ID is automatically extracted from this parameter
// const templateName = 'projects/YOUR_PROJECT_ID/inspectTemplates/#####'

// Construct template-deletion request
const request = {
  name: templateName,
};

try {
  // Run template-deletion request
  await dlp.deleteInspectTemplate(request);
  console.log(`Successfully deleted template ${templateName}.`);
} catch (err) {
  console.log(`Error in deleteInspectTemplate: ${err.message || err}`);
}

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.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = dlp.project_path(project)

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

    # Call the API.
    dlp.delete_inspect_template(template_resource)

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

Go

// deleteInspectTemplate deletes the given template.
func deleteInspectTemplate(w io.Writer, client *dlp.Client, templateID string) {
	req := &dlppb.DeleteInspectTemplateRequest{
		Name: templateID,
	}
	err := client.DeleteInspectTemplate(context.Background(), req)
	if err != nil {
		log.Fatalf("error deleting inspect template: %v", err)
	}
	fmt.Fprintf(w, "Successfully deleted inspect template %v", templateID)
}

PHP

use Google\Cloud\Dlp\V2\DlpServiceClient;

/**
 * Delete a DLP inspection configuration template.
 *
 * @param string $templateId The name of the template to delete.
 *        Parent project ID is automatically extracted from this parameter
 */
function delete_inspect_templates($templateId)
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run template deletion request
    $dlp->deleteInspectTemplate($templateId);

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

C#

public static object DeleteInspectTemplate(string projectId, string templateName)
{
    DlpServiceClient client = DlpServiceClient.Create();

    var request = new DeleteInspectTemplateRequest
    {
        Name = templateName
    };

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

    return templateName;
}

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Data Loss Prevention