Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples
As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Use EnableBaseline com um AWS SDK
Os exemplos de código a seguir mostram como usar o EnableBaseline.
Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação em contexto no seguinte exemplo de código:
- .NET
-
- SDK para .NET (v4)
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository
. /// <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; } }-
Para obter detalhes da API, consulte EnableBaselinea Referência AWS SDK para .NET da API.
-
- Java
-
- SDK para Java 2.x
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository
. /** * 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 }); }-
Para obter detalhes da API, consulte EnableBaselinea Referência AWS SDK for Java 2.x da API.
-
- Python
-
- SDK para Python (Boto3)
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository
. 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-
Para obter detalhes da API, consulte a EnableBaselineReferência da API AWS SDK for Python (Boto3).
-