Utilizzare con un SDK EnableBaselineAWS - AWS Esempi di codice SDK

Sono disponibili altri esempi AWS SDK nel repository AWS Doc SDK Examples. GitHub

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare con un SDK EnableBaselineAWS

Gli esempi di codice seguenti mostrano come utilizzare EnableBaseline.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

.NET
SDK per .NET (v4)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Enable a baseline for the specified target. /// </summary> /// <param name="targetIdentifier">The ARN of the target.</param> /// <param name="baselineIdentifier">The identifier of baseline to enable.</param> /// <param name="baselineVersion">The version of baseline to enable.</param> /// <param name="identityCenterBaseline">The identifier of identity center baseline if it is enabled.</param> /// <returns>The enabled baseline ARN or null.</returns> public async Task<string?> EnableBaselineAsync(string targetIdentifier, string baselineIdentifier, string baselineVersion, string identityCenterBaseline) { try { var parameters = new List<EnabledBaselineParameter>(); if (!string.IsNullOrEmpty(identityCenterBaseline)) { parameters.Add( new EnabledBaselineParameter { Key = "IdentityCenterEnabledBaselineArn", Value = identityCenterBaseline }); } var request = new EnableBaselineRequest { BaselineIdentifier = baselineIdentifier, BaselineVersion = baselineVersion, TargetIdentifier = targetIdentifier, Parameters = parameters }; var response = await _controlTowerService.EnableBaselineAsync(request); var operationId = response.OperationIdentifier; // Wait for operation to complete while (true) { var status = await GetBaselineOperationAsync(operationId); Console.WriteLine($"Baseline operation status: {status}"); if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED) { break; } await Task.Delay(30000); // Wait 30 seconds } return response.Arn; } catch (ValidationException ex) { if (ex.Message.Contains("already enabled")) Console.WriteLine("Baseline is already enabled for this target"); else { Console.WriteLine(ex.Message); } // Write the message and return null if baseline cannot be enabled. return null; } catch (AmazonControlTowerException ex) { Console.WriteLine($"Couldn't enable baseline. Here's why: {ex.ErrorCode}: {ex.Message}"); throw; } }
  • Per i dettagli sull'API, consulta la EnableBaselinesezione AWS SDK per .NET API Reference.

Java
SDK per Java 2.x
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/** * Asynchronously enables a baseline for the specified target if not already enabled. * * @param targetIdentifier The ARN of the target (OU or account). * @param baselineIdentifier The baseline definition ARN to enable. * @param baselineVersion The baseline version to enable. * @return A CompletableFuture containing the enabled baseline ARN, or null if already enabled. */ public CompletableFuture<String> enableBaselineAsync( String targetIdentifier, String baselineIdentifier, String baselineVersion ) { EnableBaselineRequest request = EnableBaselineRequest.builder() .baselineIdentifier(baselineIdentifier) .baselineVersion(baselineVersion) .targetIdentifier(targetIdentifier) .build(); return getAsyncClient().enableBaseline(request) .handle((resp, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ControlTowerException e) { String code = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN"; String msg = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage(); if ("ValidationException".equals(code) && msg.contains("already enabled")) { System.out.println("Baseline is already enabled for this target → fetching ARN..."); return fetchEnabledBaselineArn(targetIdentifier, baselineIdentifier) .join(); // fetch existing ARN synchronously } throw new RuntimeException("Error enabling baseline: " + code + " - " + msg, e); } throw new RuntimeException("Unexpected error enabling baseline: " + cause.getMessage(), cause); } return resp; }) .thenCompose(result -> { if (result instanceof EnableBaselineResponse resp) { String operationId = resp.operationIdentifier(); String enabledBaselineArn = resp.arn(); System.out.println("Baseline enable started. ARN: " + enabledBaselineArn + ", operation ID: " + operationId); // Inline polling return CompletableFuture.supplyAsync(() -> { while (true) { GetBaselineOperationRequest opReq = GetBaselineOperationRequest.builder() .operationIdentifier(operationId) .build(); GetBaselineOperationResponse opResp = getAsyncClient().getBaselineOperation(opReq).join(); BaselineOperation op = opResp.baselineOperation(); BaselineOperationStatus status = op.status(); System.out.println("Operation " + operationId + " status: " + status); if (status == BaselineOperationStatus.SUCCEEDED) { return enabledBaselineArn; } else if (status == BaselineOperationStatus.FAILED) { String opId = op.operationIdentifier(); String reason = op.statusMessage() != null ? op.statusMessage() : "No failure reason provided"; throw new RuntimeException("Baseline operation failed (ID: " + opId + "), status: " + status + ", reason: " + reason); } try { Thread.sleep(Duration.ofSeconds(15).toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } }); } else if (result instanceof String existingArn) { // Already enabled branch return CompletableFuture.completedFuture(existingArn); } return CompletableFuture.completedFuture(null); }); } /** * Fetches the ARN of an already-enabled baseline for the target asynchronously. */ private CompletableFuture<String> fetchEnabledBaselineArn(String targetIdentifier, String baselineIdentifier) { return getAsyncClient().listEnabledBaselines(ListEnabledBaselinesRequest.builder().build()) .thenApply(listResp -> { for (EnabledBaselineSummary eb : listResp.enabledBaselines()) { if (baselineIdentifier.equals(eb.baselineIdentifier()) && targetIdentifier.equals(eb.targetIdentifier())) { return eb.arn(); } } return null; // not yet available }); }
  • Per i dettagli sull'API, consulta la EnableBaselinesezione AWS SDK for Java 2.x API Reference.

Python
SDK per Python (Boto3)
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

class ControlTowerWrapper: """Encapsulates AWS Control Tower and Control Catalog functionality.""" def __init__( self, controltower_client: boto3.client, controlcatalog_client: boto3.client ): """ :param controltower_client: A Boto3 Amazon ControlTower client. :param controlcatalog_client: A Boto3 Amazon ControlCatalog client. """ self.controltower_client = controltower_client self.controlcatalog_client = controlcatalog_client @classmethod def from_client(cls): controltower_client = boto3.client("controltower") controlcatalog_client = boto3.client("controlcatalog") return cls(controltower_client, controlcatalog_client) def enable_baseline( self, target_identifier: str, identity_center_baseline: str, baseline_identifier: str, baseline_version: str, ): """ Enables a baseline for the specified target if it's not already enabled. :param target_identifier: The ARN of the target. :param baseline_identifier: The identifier of baseline to enable. :param identity_center_baseline: The identifier of identity center baseline if it is enabled. :param baseline_version: The version of baseline to enable. :return: The enabled baseline ARN or None if already enabled. :raises ClientError: If enabling the baseline fails for reasons other than it being already enabled. """ try: # Only include parameters if identity_center_baseline is not empty parameters = [] if identity_center_baseline: parameters = [ { "key": "IdentityCenterEnabledBaselineArn", "value": identity_center_baseline, } ] response = self.controltower_client.enable_baseline( baselineIdentifier=baseline_identifier, baselineVersion=baseline_version, targetIdentifier=target_identifier, parameters=parameters, ) operation_id = response["operationIdentifier"] while True: status = self.get_baseline_operation(operation_id) print(f"Baseline operation status: {status}") if status in ["SUCCEEDED", "FAILED"]: break time.sleep(30) return response["arn"] except ClientError as err: if err.response["Error"]["Code"] == "ValidationException": if "already enabled" in err.response["Error"]["Message"]: print("Baseline is already enabled for this target") else: print( "Unable to enable baseline due to validation exception: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) logger.error( "Couldn't enable baseline. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) return None
  • Per i dettagli sull'API, consulta EnableBaseline AWSSDK for Python (Boto3) API Reference.