Aggiungere contrassegni di sicurezza agli asset

Dimostra l'aggiunta di contrassegni di sicurezza agli asset

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

Go

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// addSecurityMarks adds/updates the security marks for the assetName.
// Specifically, it sets "key_a" and "key_b" to "value_a" and "value_b"
// respectively.  assetName is the resource path for an asset.
func addSecurityMarks(w io.Writer, assetName string) error {
	// Specify the value of 'assetName' in one of the following formats:
	// 		assetName := "organizations/{org_id}/assets/{asset_id}"
	//		assetName := "projects/{project_id}/assets/{asset_id}"
	//		assetName := "folders/{folder_id}/assets/{asset_id}"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.UpdateSecurityMarksRequest{
		// If not set or empty, all marks would be cleared before
		// adding the new marks below.
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"marks.key_a", "marks.key_b"},
		},
		SecurityMarks: &securitycenterpb.SecurityMarks{
			Name: fmt.Sprintf("%s/securityMarks", assetName),
			// Note keys correspond to the last part of each path.
			Marks: map[string]string{"key_a": "value_a", "key_b": "value_b"},
		},
	}
	updatedMarks, err := client.UpdateSecurityMarks(ctx, req)
	if err != nil {
		return fmt.Errorf("UpdateSecurityMarks: %w", err)
	}

	fmt.Fprintf(w, "Updated marks: %s\n", updatedMarks.Name)
	for k, v := range updatedMarks.Marks {
		fmt.Fprintf(w, "%s = %s\n", k, v)
	}
	return nil

}

Java

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

static SecurityMarks addToAsset(String assetName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Specify the value of 'assetName' in one of the following formats:
    //    String assetName = "organizations/{org-id}/assets/{asset-id}";
    //    String assetName = "projects/{project-id}/assets/{asset-id}";
    //    String assetName = "folders/{folder-id}/assets/{asset-id}";
    //
    // Start setting up a request to add security marks for an asset.
    ImmutableMap markMap = ImmutableMap.of("key_a", "value_a", "key_b", "value_b");

    // Add security marks and field mask for security marks.
    SecurityMarks securityMarks =
        SecurityMarks.newBuilder()
            .setName(assetName + "/securityMarks")
            .putAllMarks(markMap)
            .build();
    FieldMask updateMask =
        FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build();

    UpdateSecurityMarksRequest request =
        UpdateSecurityMarksRequest.newBuilder()
            .setSecurityMarks(securityMarks)
            .setUpdateMask(updateMask)
            .build();

    // Call the API.
    SecurityMarks response = client.updateSecurityMarks(request);

    System.out.println("Security Marks:");
    System.out.println(response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Node.js

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();

async function addSecurityMarks() {
  // assetName is the full resource path for the asset to update.
  /*
   * TODO(developer): Uncomment the following lines
   */
  // Specify the value of 'assetName' in one of the following formats:
  //    `organizations/${org-id}/assets/${asset-id}`;
  //    `projects/${project-id}/assets/${asset-id}`;
  //    `folders/${folder-id}/assets/${asset-id}`;
  // const assetName = "organizations/123123342/assets/12312321";
  const [newMarks] = await client.updateSecurityMarks({
    securityMarks: {
      name: `${assetName}/securityMarks`,
      marks: {key_a: 'value_a', key_b: 'value_b'},
    },
    // Only update the marks with these keys.
    updateMask: {paths: ['marks.key_a', 'marks.key_b']},
  });

  console.log('New marks: %', newMarks);
}
addSecurityMarks();

Python

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import securitycenter
from google.protobuf import field_mask_pb2

# Create a new client.
client = securitycenter.SecurityCenterClient()

# 'asset_name' is the resource path for an asset that exists in SCC.
# Specify the value of 'asset_name' in one of the following formats:
#   f"organizations/{org_id}/assets/{asset_id}"
#   f"projects/{project_id}/assets/{asset_id}"
#   f"folders/{folder_id}/assets/{asset_id}"
# asset_name = organizations/123123342/assets/12312321
marks_name = f"{asset_name}/securityMarks"

# Notice the suffix after "marks." in the field mask matches the keys
# in marks.
field_mask = field_mask_pb2.FieldMask(paths=["marks.key_a", "marks.key_b"])
marks = {"key_a": "value_a", "key_b": "value_b"}

updated_marks = client.update_security_marks(
    request={
        "security_marks": {"name": marks_name, "marks": marks},
        "update_mask": field_mask,
    }
)
print(updated_marks)

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.