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

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

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 for .NET (v4)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

/// <summary> /// List enabled controls for a target organizational unit. /// </summary> /// <param name="targetIdentifier">The target organizational unit identifier.</param> /// <returns>A list of enabled control summaries.</returns> public async Task<List<EnabledControlSummary>> ListEnabledControlsAsync(string targetIdentifier) { try { var request = new ListEnabledControlsRequest { TargetIdentifier = targetIdentifier }; var enabledControls = new List<EnabledControlSummary>(); var enabledControlsPaginator = _controlTowerService.Paginators.ListEnabledControls(request); await foreach (var response in enabledControlsPaginator.Responses) { enabledControls.AddRange(response.EnabledControls); } return enabledControls; } catch (Amazon.ControlTower.Model.ResourceNotFoundException ex) when (ex.Message.Contains("not registered with AWS Control Tower")) { Console.WriteLine("AWS Control Tower must be enabled to work with enabling controls."); return new List<EnabledControlSummary>(); } catch (AmazonControlTowerException ex) { Console.WriteLine($"Couldn't list enabled controls. Here's why: {ex.ErrorCode}: {ex.Message}"); throw; } }
  • Para obter detalhes da API, consulte ListEnabledControlsa Referência AWS SDK for .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.

/** * Lists all enabled controls for a specific target using pagination. * * @param targetIdentifier the identifier of the target (e.g., OU ARN) * @return a list of enabled controls * @throws ControlTowerException if a service-specific error occurs * @throws SdkException if an SDK error occurs */ public CompletableFuture<List<EnabledControlSummary>> listEnabledControlsAsync(String targetIdentifier) { System.out.println("Starting list enabled controls paginator for target " + targetIdentifier); ListEnabledControlsRequest request = ListEnabledControlsRequest.builder() .targetIdentifier(targetIdentifier) .build(); ListEnabledControlsPublisher paginator = getAsyncClient().listEnabledControlsPaginator(request); List<EnabledControlSummary> enabledControls = new ArrayList<>(); // Subscribe to the paginator asynchronously return paginator.subscribe(response -> { if (response.enabledControls() != null && !response.enabledControls().isEmpty()) { response.enabledControls().forEach(control -> { enabledControls.add(control); }); } else { System.out.println("Page contained no enabled controls."); } }) .thenRun(() -> System.out.println( "Successfully retrieved "+enabledControls.size() +" enabled controls for target "+targetIdentifier )) .thenApply(v -> enabledControls) .exceptionally(ex -> { Throwable cause = ex.getCause() != null ? ex.getCause() : ex; if (cause instanceof ControlTowerException e) { String errorCode = e.awsErrorDetails().errorCode(); switch (errorCode) { case "AccessDeniedException": throw new CompletionException( "Access denied when listing enabled controls: %s".formatted(e.getMessage()), e); case "ResourceNotFoundException": if (e.getMessage() != null && e.getMessage().contains("not registered with AWS Control Tower")) { throw new CompletionException( "Control Tower must be enabled to work with controls", e); } throw new CompletionException( "Target not found when listing enabled controls: %s".formatted(e.getMessage()), e); default: throw new CompletionException( "Error listing enabled controls: %s".formatted(e.getMessage()), e); } } if (cause instanceof SdkException) { throw new CompletionException( "SDK error listing enabled controls: %s".formatted(cause.getMessage()), cause); } throw new CompletionException("Failed to list enabled controls", cause); }); }
  • Para obter detalhes da API, consulte ListEnabledControlsa 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 list_enabled_controls(self, target_identifier: str): """ Lists all enabled controls for a specific target. :param target_identifier: The identifier of the target (e.g., OU ARN). :return: List of enabled controls. :raises ClientError: If the listing operation fails. """ enabled_controls = [] try: paginator = self.controltower_client.get_paginator("list_enabled_controls") for page in paginator.paginate(targetIdentifier=target_identifier): enabled_controls.extend(page["enabledControls"]) return enabled_controls except ClientError as err: if err.response["Error"]["Code"] == "AccessDeniedException": logger.error( "Access denied. Please ensure you have the necessary permissions." ) return enabled_controls elif ( err.response["Error"]["Code"] == "ResourceNotFoundException" and "not registered with AWS Control Tower" in err.response["Error"]["Message"] ): logger.error("Control Tower must be enabled to work with controls.") return enabled_controls else: logger.error( "Couldn't list enabled controls. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • Para obter detalhes da API, consulte a ListEnabledControlsReferência da API AWS SDK for Python (Boto3).