Atualize um módulo personalizado de Deteção de ameaças de eventos

Código de exemplo para atualizar módulos personalizados da Deteção de ameaças de eventos.

Exemplo de código

Go

Para se autenticar no Security Command Center, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.


import (
	"context"
	"fmt"
	"io"

	securitycentermanagement "cloud.google.com/go/securitycentermanagement/apiv1"
	securitycentermanagementpb "cloud.google.com/go/securitycentermanagement/apiv1/securitycentermanagementpb"
	fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateEventThreatDetectionCustomModule updates a custom module for Event Threat Detection.
func updateEventThreatDetectionCustomModule(w io.Writer, parent string, customModuleID string) error {
	// parent: Use any one of the following options:
	// - organizations/{organization_id}/locations/{location_id}
	// - folders/{folder_id}/locations/{location_id}
	// - projects/{project_id}/locations/{location_id}

	ctx := context.Background()
	client, err := securitycentermanagement.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycentermanagement.NewClient: %w", err)
	}
	defer client.Close()

	// Define the custom module configuration
	customModule := &securitycentermanagementpb.EventThreatDetectionCustomModule{
		Name:            fmt.Sprintf("%s/eventThreatDetectionCustomModules/%s", parent, customModuleID),
		EnablementState: securitycentermanagementpb.EventThreatDetectionCustomModule_DISABLED,
	}

	req := &securitycentermanagementpb.UpdateEventThreatDetectionCustomModuleRequest{
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"enablement_state",
			},
		},
		EventThreatDetectionCustomModule: customModule,
	}

	module, err := client.UpdateEventThreatDetectionCustomModule(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update EventThreatDetectionCustomModule: %w", err)
	}

	fmt.Fprintf(w, "Updated EventThreatDetectionCustomModule: %s\n", module.Name)
	return nil
}

Java

Para se autenticar no Security Command Center, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

import com.google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule;
import com.google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule.EnablementState;
import com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementClient;
import com.google.cloud.securitycentermanagement.v1.UpdateEventThreatDetectionCustomModuleRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class UpdateEventThreatDetectionCustomModule {

  public static void main(String[] args) throws IOException {
    // TODO: Developer should replace project_id with a real project ID before running this code
    String projectId = "project_id";

    String customModuleId = "custom_module_id";

    updateEventThreatDetectionCustomModule(projectId, customModuleId);
  }

  public static EventThreatDetectionCustomModule updateEventThreatDetectionCustomModule(
      String projectId, String customModuleId) 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.
    try (SecurityCenterManagementClient client = SecurityCenterManagementClient.create()) {

      String qualifiedModuleName =
          String.format(
              "projects/%s/locations/global/eventThreatDetectionCustomModules/%s",
              projectId, customModuleId);

      // Define the event threat detection custom module configuration, update the
      // DisplayName and EnablementState accordingly.
      EventThreatDetectionCustomModule eventThreatDetectionCustomModule =
          EventThreatDetectionCustomModule.newBuilder()
              .setName(qualifiedModuleName)
              .setDisplayName("updated_custom_module_name")
              .setEnablementState(EnablementState.DISABLED)
              .build();

      // Set the field mask to specify which properties should be updated. In the below example we
      // are updating displayName and EnablementState
      // https://cloud.google.com/security-command-center/docs/reference/security-center-management/rest/v1/organizations.locations.eventThreatDetectionCustomModules/patch#query-parameters
      // https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
      FieldMask fieldMask =
          FieldMask.newBuilder().addPaths("display_name").addPaths("enablement_state").build();

      UpdateEventThreatDetectionCustomModuleRequest request =
          UpdateEventThreatDetectionCustomModuleRequest.newBuilder()
              .setEventThreatDetectionCustomModule(eventThreatDetectionCustomModule)
              .setUpdateMask(fieldMask)
              .build();

      EventThreatDetectionCustomModule response =
          client.updateEventThreatDetectionCustomModule(request);

      return response;
    }
  }
}

Node.js

Para se autenticar no Security Command Center, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

// Imports the Google Cloud client library.
const {SecurityCenterManagementClient} =
  require('@google-cloud/securitycentermanagement').v1;

// Create a Security Center Management client
const client = new SecurityCenterManagementClient();

/*
 * Required. Resource name of event threat detection module.
 *     Its format is
 *    `organizations/[organization_id]/locations/[location_id]/eventThreatDetectionCustomModules/[custom_module]`
 *    `folders/[folder_id]/locations/[location_id]/eventThreatDetectionCustomModules/[custom_module]`
 *    `projects/[project_id]/locations/[location_id]/eventThreatDetectionCustomModules/[custom_module]`
 */
// TODO(developer): Update the following references for your own environment before running the sample.
// const organizationId = 'YOUR_ORGANIZATION_ID';
// const location = 'LOCATION_ID';
// const customModuleId = 'CUSTOM_MODULE_ID';
const name = `organizations/${organizationId}/locations/${location}/eventThreatDetectionCustomModules/${customModuleId}`;

// Define the event threat detection custom module configuration, update the
// EnablementState accordingly.
const eventThreatDetectionCustomModule = {
  name: name,
  enablementState: 'DISABLED',
};

// Set the field mask to specify which properties should be updated.
const fieldMask = {
  paths: ['enablement_state'],
};

// Build the request.
const updateEventThreatDetectionCustomModuleRequest = {
  eventThreatDetectionCustomModule: eventThreatDetectionCustomModule,
  updateMask: fieldMask,
};

async function updateEventThreatDetectionCustomModule() {
  // Call the API.
  const [response] = await client.updateEventThreatDetectionCustomModule(
    updateEventThreatDetectionCustomModuleRequest
  );
  console.log('Updated EventThreatDetectionCustomModule: %j', response);
}

updateEventThreatDetectionCustomModule();

Python

Para se autenticar no Security Command Center, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

def update_event_threat_detection_custom_module(parent: str, module_id: str):
    """
    Updates an Event Threat Detection Custom Module.

    Args:
        parent: Use any one of the following options:
                - organizations/{organization_id}/locations/{location_id}
                - folders/{folder_id}/locations/{location_id}
                - projects/{project_id}/locations/{location_id}
    Returns:
        EventThreatDetectionCustomModule
    """
    client = securitycentermanagement_v1.SecurityCenterManagementClient()

    try:

        custom_module = securitycentermanagement_v1.EventThreatDetectionCustomModule(
            name=f"{parent}/eventThreatDetectionCustomModules/{module_id}",
            enablement_state=securitycentermanagement_v1.EventThreatDetectionCustomModule.EnablementState.DISABLED,
        )

        # Create the request
        request = securitycentermanagement_v1.UpdateEventThreatDetectionCustomModuleRequest(
            event_threat_detection_custom_module=custom_module,
            update_mask=FieldMask(paths=["enablement_state"]),
        )

        # Make the API call
        response = client.update_event_threat_detection_custom_module(request=request)

        print(f"Updated EventThreatDetectionCustomModule: {response.name}")
        return response

    except Exception as e:
        print(f"Failed to update EventThreatDetectionCustomModule: {e}")
        raise

O que se segue?

Para pesquisar e filtrar exemplos de código para outros Google Cloud produtos, consulte o Google Cloud navegador de exemplos.