View a markdown version of this page

Uso ListKeys con un AWS SDK o CLI - AWS Key Management Service

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à.

Uso ListKeys con un AWS SDK o CLI

I seguenti esempi di codice mostrano come usare ListKeys.

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
Nota

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

using System; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; /// <summary> /// List the AWS Key Managements Service (AWS KMS) keys for the AWS Region /// of the default user. To list keys in another AWS Region, supply the Region /// as a parameter to the client constructor. /// </summary> public class ListKeys { public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); var request = new ListKeysRequest(); var response = new ListKeysResponse(); do { response = await client.ListKeysAsync(request); response.Keys.ForEach(key => { Console.WriteLine($"ID: {key.KeyId}, {key.KeyArn}"); }); // Set the Marker property when response.Truncated is true // in order to get the next keys. request.Marker = response.NextMarker; } while (response.Truncated); } }
  • Per i dettagli sull'API, vedi ListKeys nel AWS SDK per .NET Riferimento API.

CLI
AWS CLI

Come ottenere le chiavi KMS in un account e in una Regione

L’esempio list-keys seguente ottiene le chiavi KMS in un account e in una Regione. Questo comando restituisce entrambi AWS chiavi gestite e chiavi gestite dal cliente.

aws kms list-keys

Output:

{ "Keys": [ { "KeyArn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }, { "KeyArn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222" }, { "KeyArn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333", "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333" } ] }

Per ulteriori informazioni, consulta Visualizzazione di chiavi nella Guida per gli sviluppatori del Servizio AWS di gestione delle chiavi.

  • Per i dettagli sull'API, consulta ListKeys nel AWS CLI Riferimento al comando.

Java
SDK per Java 2.x
Nota

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

import software.amazon.awssdk.services.kms.KmsAsyncClient; import software.amazon.awssdk.services.kms.model.ListKeysRequest; import software.amazon.awssdk.services.kms.paginators.ListKeysPublisher; import java.util.concurrent.CompletableFuture; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class HelloKMS { public static void main(String[] args) { listAllKeys(); } public static void listAllKeys() { KmsAsyncClient kmsAsyncClient = KmsAsyncClient.builder() .build(); ListKeysRequest listKeysRequest = ListKeysRequest.builder() .limit(15) .build(); /* * The `subscribe` method is required when using paginator methods in the AWS SDK * because paginator methods return an instance of a `ListKeysPublisher`, which is * based on a reactive stream. This allows asynchronous retrieval of paginated * results as they become available. By subscribing to the stream, we can process * each page of results as they are emitted. */ ListKeysPublisher keysPublisher = kmsAsyncClient.listKeysPaginator(listKeysRequest); CompletableFuture<Void> future = keysPublisher .subscribe(r -> r.keys().forEach(key -> System.out.println("The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId()))) .whenComplete((result, exception) -> { if (exception != null) { System.err.println("Error occurred: " + exception.getMessage()); } else { System.out.println("Successfully listed all keys."); } }); try { future.join(); } catch (Exception e) { System.err.println("Failed to list keys: " + e.getMessage()); } } }
  • Per i dettagli sull'API, vedi ListKeys nel AWS SDK for Java 2.x Riferimento API.

Kotlin
SDK per Kotlin
Nota

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

suspend fun listAllKeys() { val request = ListKeysRequest { limit = 15 } KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.listKeys(request) response.keys?.forEach { key -> println("The key ARN is ${key.keyArn}") println("The key Id is ${key.keyId}") } } }
  • Per i dettagli sull'API, vedi ListKeys nel AWS Riferimento all'API SDK per Kotlin.

PHP
SDK per PHP
Nota

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

/*** * @return array */ public function listKeys() { try { $contents = []; $paginator = $this->client->getPaginator("ListKeys"); foreach($paginator as $result){ foreach ($result['Content'] as $object) { $contents[] = $object; } } return $contents; }catch(KmsException $caught){ echo "There was a problem listing the keys: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
  • Per i dettagli sull'API, vedi ListKeys nel AWS SDK per PHP Riferimento API.

Python
SDK for Python (Boto3)
Nota

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

class KeyManager: def __init__(self, kms_client): self.kms_client = kms_client self.created_keys = [] @classmethod def from_client(cls) -> "KeyManager": """ Creates a KeyManager instance with a default KMS client. :return: An instance of KeyManager initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def list_keys(self): """ Lists the keys for the current account by using a paginator. """ try: page_size = 10 print("\nLet's list your keys.") key_paginator = self.kms_client.get_paginator("list_keys") for key_page in key_paginator.paginate(PaginationConfig={"PageSize": 10}): print(f"Here are {len(key_page['Keys'])} keys:") pprint(key_page["Keys"]) if key_page["Truncated"]: answer = input( f"Do you want to see the next {page_size} keys (y/n)? " ) if answer.lower() != "y": break else: print("That's all your keys!") except ClientError as err: logging.error( "Couldn't list your keys. Here's why: %s", err.response["Error"]["Message"], )
  • Per i dettagli sull'API, vedi ListKeys nel AWS Riferimento alle API SDK per Python (Boto3).

Rust
SDK per Rust
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.

async fn show_keys(client: &Client) -> Result<(), Error> { let resp = client.list_keys().send().await?; let keys = resp.keys.unwrap_or_default(); let len = keys.len(); for key in keys { println!("Key ARN: {}", key.key_arn.as_deref().unwrap_or_default()); } println!(); println!("Found {} keys", len); Ok(()) }
  • Per i dettagli sull'API, vedi ListKeys nel AWS SDK per Rust API di riferimento.

SAP ABAP
SDK per SAP ABAP
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.

TRY. oo_result = lo_kms->listkeys( ). MESSAGE 'Retrieved KMS keys list.' TYPE 'I'. CATCH /aws1/cx_kmskmsinternalex. MESSAGE 'An internal error occurred.' TYPE 'E'. ENDTRY.
  • Per i dettagli sull'API, vedi ListKeys nel AWS Riferimento all'API SDK per SAP ABAP.

Per un elenco completo di AWS Guide per sviluppatori SDK ed esempi di codice, consulta L'utilizzo di questo servizio con un AWS SDK. Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.