Use DisableControl com um AWS SDK - AWS Exemplos de código do SDK

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

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 DisableControl com um AWS SDK

Os exemplos de código a seguir mostram como usar o DisableControl.

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> /// Disable a control for a specified target. /// </summary> /// <param name="controlArn">The ARN of the control to disable.</param> /// <param name="targetIdentifier">The identifier of the target (e.g., OU ARN).</param> /// <returns>The operation ID.</returns> public async Task<string> DisableControlAsync(string controlArn, string targetIdentifier) { try { var request = new DisableControlRequest { ControlIdentifier = controlArn, TargetIdentifier = targetIdentifier }; var response = await _controlTowerService.DisableControlAsync(request); var operationId = response.OperationIdentifier; // Wait for operation to complete while (true) { var status = await GetControlOperationAsync(operationId); Console.WriteLine($"Control operation status: {status}"); if (status == ControlOperationStatus.SUCCEEDED || status == ControlOperationStatus.FAILED) { break; } await Task.Delay(30000); // Wait 30 seconds } return operationId; } catch (Amazon.ControlTower.Model.ResourceNotFoundException) { Console.WriteLine("Control not found."); throw; } catch (AmazonControlTowerException ex) { Console.WriteLine($"Couldn't disable control. Here's why: {ex.ErrorCode}: {ex.Message}"); throw; } }
  • Para obter detalhes da API, consulte DisableControla 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.

/** * Disables a control for a specified target. * * @param controlIdentifier the identifier of the control to disable * @param targetIdentifier the identifier of the target (e.g., OU ARN) * @return the operation identifier * @throws ControlTowerException if a service-specific error occurs * @throws SdkException if an SDK error occurs */ public CompletableFuture<String> disableControlAsync( String controlIdentifier, String targetIdentifier) { DisableControlRequest request = DisableControlRequest.builder() .controlIdentifier(controlIdentifier) .targetIdentifier(targetIdentifier) .build(); return getAsyncClient().disableControl(request) .thenCompose(response -> { String operationId = response.operationIdentifier(); System.out.println("Disable control operation started. Operation ID: " + operationId); CompletableFuture<String> resultFuture = new CompletableFuture<>(); Runnable poller = new Runnable() { @Override public void run() { getControlOperationAsync(operationId) .thenAccept(status -> { System.out.println("Control operation status: " + status); if (status == ControlOperationStatus.SUCCEEDED || status == ControlOperationStatus.FAILED) { resultFuture.complete(operationId); } else { // poll again after 30 seconds CompletableFuture.delayedExecutor(30, TimeUnit.SECONDS) .execute(this); } }) .exceptionally(ex -> { resultFuture.completeExceptionally(ex); return null; }); } }; // start polling immediately poller.run(); return resultFuture; }) .exceptionally(ex -> { Throwable cause = ex.getCause() != null ? ex.getCause() : ex; if (cause instanceof ControlTowerException e) { String errorCode = e.awsErrorDetails().errorCode(); if ("ResourceNotFoundException".equals(errorCode)) { // SPEC: notify user and continue System.out.println("Control not found for disabling: " + e.getMessage()); return null; } throw new CompletionException( "Error disabling control: " + e.getMessage(), e); } if (cause instanceof SdkException) { throw new CompletionException( "SDK error disabling control: " + cause.getMessage(), cause); } throw new CompletionException( "Failed to disable control", cause); }); }
  • Para obter detalhes da API, consulte DisableControla 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 disable_control(self, control_arn: str, target_identifier: str): """ Disables a control for a specified target. :param control_arn: The ARN of the control to disable. :param target_identifier: The identifier of the target (e.g., OU ARN). :return: The operation ID. :raises ClientError: If disabling the control fails. """ try: response = self.controltower_client.disable_control( controlIdentifier=control_arn, targetIdentifier=target_identifier ) operation_id = response["operationIdentifier"] while True: status = self.get_control_operation(operation_id) print(f"Control operation status: {status}") if status in ["SUCCEEDED", "FAILED"]: break time.sleep(30) return operation_id except ClientError as err: if err.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Control not found.") else: logger.error( "Couldn't disable control. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • Para obter detalhes da API, consulte a DisableControlReferência da API AWS SDK for Python (Boto3).