Como criar modelos de inspeção do Cloud DLP

Neste tópico, você conhecerá os detalhes da criação de um novo modelo de inspeção. Para ver instruções rápidas sobre como criar um novo modelo de inspeção usando a IU do Cloud Data Loss Prevention (DLP), consulte o Guia de início rápido: como criar um modelo de inspeção do Cloud DLP.

Sobre modelos

Com os modelos, é possível criar e manter informações de configuração para usar com o Cloud DLP. Os modelos são úteis para desassociar informações de configuração da implementação das solicitações como, por exemplo, o que você inspeciona e como faz a desidentificação disso. Os modelos fornecem uma maneira de reutilizar a configuração e ter consistência entre usuários e conjuntos de dados. Além disso, sempre que você atualiza um modelo, ele é atualizado para qualquer gatilho de job que o use.

O Cloud DLP oferece suporte a modelos de inspeção, discutidos neste tópico, e a modelos de desidentificação, discutidos em Como criar modelos de desidentificação do Cloud DLP.

Para informações conceituais sobre modelos no Cloud DLP, consulte Modelos.

Criar um novo modelo de inspeção

Para criar um novo modelo do Cloud DLP:

Console

  1. No Console do Cloud, abra o Cloud DLP.

    Acessar a IU do Cloud DLP

  2. No menu Criar, escolha Modelo.

    Captura de tela da IU do DLP com o menu Criar > Modelos selecionado.

    Como alternativa, clique no seguinte botão:

    Criar novo modelo

A página "Criar Modelo" contém as seguintes seções:

Definir modelo

Em Definir modelo, insira um identificador para o modelo de inspeção. É assim que você fará referência ao modelo quando executar um job, criar um gatilho de job e assim por diante. Use letras, números e hifens. Se quiser, você também pode inserir um nome de exibição mais adequado a pessoas, além de uma descrição para lembrar melhor o que o modelo faz.

Configurar detecção

Em seguida, configure o que o Cloud DLP detecta no seu conteúdo escolhendo um infoType e outras opções.

Os detectores de InfoType encontram dados confidenciais de um determinado tipo. Por exemplo, o detector de infoType do Cloud DLP US_SOCIAL_SECURITY_NUMBER encontra números da Previdência Social dos EUA. Além dos detectores de infoType integrados, é possível criar seus próprios detectores de infoType personalizados.

Em InfoTypes, escolha o detector de infoType correspondente a um tipo de dado que você quer verificar. Também é possível deixar esse campo em branco para verificar todos os infoTypes padrão. Mais informações sobre cada detector são fornecidas na referência de detectores de InfoType.

Também é possível adicionar detectores de infoType personalizados na seção infoTypes personalizados e personalizar os detectores de infoType integrados e personalizados na seção Conjuntos de regras de inspeção.

InfoTypes personalizados

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.

Conjuntos de regras de inspeção

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.

Limite de confiança

Sempre que detecta uma correspondência potencial de dados confidenciais, o Cloud DLP atribui a ele um valor de probabilidade em uma escala de "Muito improvável" a "Muito provável". Ao definir um valor de probabilidade aqui, você está instruindo o Cloud DLP a comparar apenas os dados correspondentes a esse valor de probabilidade ou valores superiores.

O valor padrão "Possível" é suficiente para a maioria das finalidades. Se você normalmente recebe correspondências muito amplas, mova o controle deslizante para a direita. Se você recebe poucas correspondências, mova o controle deslizante para a esquerda.

Quando terminar, clique em Criar a fim de criar o modelo. A página de informações resumidas do modelo é exibida.

Para retornar à página principal do Cloud DLP, clique na seta Voltar no Console do Cloud.

Protocolo

Um modelo de inspeção é uma configuração de inspeção reutilizável, além de alguns metadados. Em termos de API, o objeto InspectTemplate é efetivamente um objeto InspectConfig que inclui mais alguns campos de metadados, como um nome de exibição e uma descrição. Portanto, para criar um novo modelo de inspeção, siga estas etapas básicas:

  1. Comece com um objeto InspectConfig.
  2. Faça chamada ou execute o comando POST do método create do recurso projects.inspectTemplates ou organizations.inspectTemplates, incluindo em sua solicitação um objeto InspectTemplate que contenha um nome de exibição, uma descrição e esse objeto InspectConfig.

O InspectTemplate retornado estará pronto para uso imediatamente. É possível referir-se a ele em outras chamadas ou jobs pelo name. É possível listar os modelos existentes chamando o método *.inspectTemplates.list. Para visualizar um modelo específico, chame o método *.inspectTemplates.get. Observe que o limite para o número de modelos que podem ser criados é 1.000.

Se já teve alguma experiência na inspeção de texto, imagens ou conteúdo estruturado em busca de conteúdo confidencial usando o Cloud DLP, você já criou um objeto InspectConfig. Uma outra etapa o transforma em um objeto InspectTemplate.

O seguinte JSON é um exemplo do que é possível enviar para o método projects.inspectTemplates.create. Esse JSON cria um novo modelo com o nome de exibição e a descrição fornecidos e verifica correspondências nos InfoTypes PHONE_NUMBER e US_TOLLFREE_PHONE_NUMBER. Ele incluirá nas descobertas até 100 correspondências com probabilidades de pelo menos POSSIBLE e incluirá um snippet de contexto para cada uma.

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

Saída JSON:

O JSON de resposta será parecido com este:

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

Para testar isso rapidamente, use as APIs Explorer incorporadas abaixo. Para informações gerais sobre como usar JSON para enviar solicitações à API Cloud DLP, consulte o guia de início rápido do JSON.

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.ProjectName;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class TemplatesCreate {

  public static void createInspectTemplate() throws IOException {
    // 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(ProjectName.of(projectId).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 callingProjectId = process.env.GCLOUD_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';

// 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: dlp.projectPath(callingProjectId),
  inspectTemplate: {
    inspectConfig: inspectConfig,
    displayName: displayName,
  },
  templateId: templateId,
};

try {
  const [response] = await dlp.createInspectTemplate(request);
  const templateName = response.name;
  console.log(`Successfully created template ${templateName}.`);
} catch (err) {
  console.log(`Error in createInspectTemplate: ${err.message || err}`);
}

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 = dlp.project_path(project)

    # Call the API.
    response = dlp.create_inspect_template(
        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:     "projects/" + 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 = $dlp->projectName($callingProjectId);
$template = $dlp->createInspectTemplate($parent, [
    'inspectTemplate' => $inspectTemplate,
    'templateId' => $templateId
]);

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

C#

public static string CreateInspectTemplate(
    string projectId,
    string templateId,
    string displayName,
    string description,
    string likelihood,
    int maxFindings,
    bool includeQuote)
{
    DlpServiceClient client = DlpServiceClient.Create();

    var request = new CreateInspectTemplateRequest
    {
        Parent = $"projects/{projectId}",
        InspectTemplate = new InspectTemplate
        {
            DisplayName = displayName,
            Description = description,
            InspectConfig = new InspectConfig
            {
                MinLikelihood = (Likelihood)Enum.Parse(typeof(Likelihood), 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.Name;
}

Usar modelos de inspeção

Depois de criar um novo modelo de inspeção, use-o ao criar um novo job de inspeção ou gatilho de job. Sempre que você atualizar esse modelo, ele será atualizado em qualquer gatilho de job que usá-lo. Para mais informações, incluindo amostras de código, consulte:

Console

Para começar a usar o novo modelo rapidamente, siga as instruções fornecidas em Guia de início rápido para criar um modelo de inspeção de do Cloud DLP com a seguinte alteração:

  • Na seção Configurar detecção > Modelos, clique no campo Nome do modelo e selecione o modelo que você acabou de criar.

Para uma explicação mais detalhada sobre como verificar seu conteúdo, consulte Como criar e programar jobs de inspeção do Cloud DLP, com atenção especial à seção "Configurar detecção".

Protocolo

Use o identificador de modelo especificado ao criar o modelo em qualquer lugar em que inspectTemplateName seja aceito, como:

Listar modelos de inspeção

Para listar todos os modelos de inspeção criados no projeto atual ou na organização:

Console

  1. No Console do Cloud, abra o Cloud DLP.

    Acessar a IU do Cloud DLP

  2. Clique na guia Modelos.

O console exibe uma lista de todos os modelos de inspeções do projeto atual.

Protocolo

Use um dos métodos *.*.list:

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.ProjectName;
import java.io.IOException;

class TemplatesList {

  public static void listInspectTemplates() throws IOException {
    // 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(ProjectName.of(projectId).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 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_v2.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

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: "projects/" + 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 = $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;
}

Excluir modelos de inspeção

Para excluir um modelo de inspeção:

Console

  1. No Console do Cloud, abra o Cloud DLP.

    Acessar a IU do Cloud DLP

  2. Clique na guia Configuração e, em seguida, na guia Modelos. O console exibe uma lista de todos os modelos do projeto atual.

  3. Na coluna Ações do modelo que você quer excluir, clique no menu Mais ações (exibido como três pontos organizados verticalmente) e clique em Excluir.

    Captura de tela dos modelos da IU do DLP com o menu

Como alternativa, na lista de modelos, clique no nome do modelo que você quer excluir. Na página de detalhes do modelo, clique em Excluir.

Protocolo

Use um dos métodos *.*.delete:

Com cada método *.*.delete, inclua o nome do recurso do modelo a ser excluído.

Java


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

class TemplatesDelete {

  public static void deleteInspectTemplate() throws IOException {
    // 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 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_v2.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

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 = $dlp->projectInspectTemplateName($callingProjectId, $templateId);
$dlp->deleteInspectTemplate($templateName);

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

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