Sono disponibili altri esempi per SDK AWS nel repository GitHub della documentazione degli esempi per SDK AWS
Utilizzare ListGrants con un SDK AWS o una CLI
Gli esempi di codice seguenti mostrano come utilizzare ListGrants.
Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. Puoi vedere questa azione nel contesto nel seguente esempio di codice:
- .NET
-
- SDK per .NET
-
Nota
Ulteriori informazioni 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 Management Service (AWS KMS) grants that are associated with /// a specific key. /// </summary> public class ListGrants { public static async Task Main() { // The identifier of the AWS KMS key to disable. You can use the // key Id or the Amazon Resource Name (ARN) of the AWS KMS key. var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab"; var client = new AmazonKeyManagementServiceClient(); var request = new ListGrantsRequest { KeyId = keyId, }; var response = new ListGrantsResponse(); do { response = await client.ListGrantsAsync(request); response.Grants.ForEach(grant => { Console.WriteLine($"{grant.GrantId}"); }); request.Marker = response.NextMarker; } while (response.Truncated); } }-
Per informazioni dettagliate sull’API, consulta ListGrants nella documentazione di riferimento dell’API AWS SDK per .NET.
-
- CLI
-
- AWS CLI
-
Come visualizzare le concessioni relative a una chiave AWS KMS
L’esempio
list-grantsseguente mostra tutte le concessioni sulla chiave KMS AWS gestita specificata per Amazon DynamoDB nel tuo account. Questa concessione consente a DynamoDB di utilizzare la chiave KMS per tuo conto per crittografare una tabella DynamoDB prima di scriverla su disco. Puoi utilizzare un comando simile per visualizzare le concessioni relative alle chiavi KMS gestite da AWS e alle chiavi KMS gestite dal cliente nell’account e nella Regione AWS.Questo comando utilizza il parametro
key-idcon un ID chiave per identificare la chiave KMS. Puoi utilizzare un ID o un ARN di chiave per identificare la chiave KMS. Per ottenere l’ID o l’ARN di chiave di una chiave KMS gestita da AWS, utilizza il comandolist-keysolist-aliases.aws kms list-grants \ --key-id1234abcd-12ab-34cd-56ef-1234567890abL’output mostra che la concessione assegna l’autorizzazione Amazon DynamoDB per utilizzare la chiave KMS per le operazioni di crittografia e visualizzare i dettagli sulla chiave KMS (
DescribeKey) e di ritirare le concessioni (RetireGrant). Il vincoloEncryptionContextSubsetlimita queste autorizzazioni alle richieste che includono le coppie di contesti di crittografia specificate. Di conseguenza, le autorizzazioni incluse nella concessione sono valide solo per l’account e la tabella DynamoDB specificati.{ "Grants": [ { "Constraints": { "EncryptionContextSubset": { "aws:dynamodb:subscriberId": "123456789012", "aws:dynamodb:tableName": "Services" } }, "IssuingAccount": "arn:aws:iam::123456789012:root", "Name": "8276b9a6-6cf0-46f1-b2f0-7993a7f8c89a", "Operations": [ "Decrypt", "Encrypt", "GenerateDataKey", "ReEncryptFrom", "ReEncryptTo", "RetireGrant", "DescribeKey" ], "GrantId": "1667b97d27cf748cf05b487217dd4179526c949d14fb3903858e25193253fe59", "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab", "RetiringPrincipal": "dynamodb.us-west-2.amazonaws.com", "GranteePrincipal": "dynamodb.us-west-2.amazonaws.com", "CreationDate": "2021-05-13T18:32:45.144000+00:00" } ] }Per ulteriori informazioni, consulta Concessioni in AWS KMS nella Guida per gli sviluppatori del Servizio AWS di gestione delle chiavi.
-
Per informazioni dettagliate sull’API, consulta ListGrants
nella documentazione di riferimento dei comandi della AWS CLI.
-
- Java
-
- SDK per Java 2.x
-
Nota
Ulteriori informazioni su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel Repository di esempi di codice AWS
. /** * Asynchronously displays the grant IDs for the specified key ID. * * @param keyId the ID of the AWS KMS key for which to list the grants * @return a {@link CompletableFuture} that, when completed, will be null if the operation succeeded, or will throw a {@link RuntimeException} if the operation failed * @throws RuntimeException if there was an error listing the grants, either due to an {@link KmsException} or an unexpected error */ public CompletableFuture<Object> displayGrantIdsAsync(String keyId) { ListGrantsRequest grantsRequest = ListGrantsRequest.builder() .keyId(keyId) .limit(15) .build(); ListGrantsPublisher paginator = getAsyncClient().listGrantsPaginator(grantsRequest); return paginator.subscribe(response -> { response.grants().forEach(grant -> { logger.info("The grant Id is: " + grant.grantId()); }); }) .thenApply(v -> null) .exceptionally(ex -> { Throwable cause = ex.getCause(); if (cause instanceof KmsException) { throw new RuntimeException("Failed to list grants: " + cause.getMessage(), cause); } else { throw new RuntimeException("An unexpected error occurred: " + cause.getMessage(), cause); } }); }-
Per informazioni dettagliate sull’API, consulta ListGrants nella documentazione di riferimento dell’API AWS SDK for Java 2.x.
-
- Kotlin
-
- SDK per Kotlin
-
Nota
Ulteriori informazioni su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel Repository di esempi di codice AWS
. suspend fun displayGrantIds(keyIdVal: String?) { val request = ListGrantsRequest { keyId = keyIdVal limit = 15 } KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.listGrants(request) response.grants?.forEach { grant -> println("The grant Id is ${grant.grantId}") } } }-
Per informazioni dettagliate sull’API, consulta ListGrants
nella documentazione di riferimento dell’API AWS SDK per Kotlin.
-
- PHP
-
- SDK per PHP
-
Nota
Ulteriori informazioni su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel Repository di esempi di codice AWS
. /*** * @param string $keyId * @return Result */ public function listGrants(string $keyId) { try{ return $this->client->listGrants([ 'KeyId' => $keyId, ]); }catch(KmsException $caught){ if($caught->getAwsErrorMessage() == "NotFoundException"){ echo " The request was rejected because the specified entity or resource could not be found.\n"; } throw $caught; } }-
Per informazioni dettagliate sull’API, consulta ListGrants nella documentazione di riferimento dell’API AWS SDK per PHP.
-
- Python
-
- SDK per Python (Boto3)
-
Nota
Ulteriori informazioni su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel Repository di esempi di codice AWS
. class GrantManager: def __init__(self, kms_client): self.kms_client = kms_client @classmethod def from_client(cls) -> "GrantManager": """ Creates a GrantManager instance with a default KMS client. :return: An instance of GrantManager initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def list_grants(self, key_id): """ Lists grants for a key. :param key_id: The ARN or ID of the key to query. :return: The grants for the key. """ try: paginator = self.kms_client.get_paginator("list_grants") grants = [] page_iterator = paginator.paginate(KeyId=key_id) for page in page_iterator: grants.extend(page["Grants"]) print(f"Grants for key {key_id}:") pprint(grants) return grants except ClientError as err: logger.error( "Couldn't list grants for key %s. Here's why: %s", key_id, err.response["Error"]["Message"], ) raise-
Per informazioni dettagliate sull’API, consulta ListGrants nella documentazione di riferimento dell’API AWS SDK per Python (Boto3).
-