Use ListGrants with an Amazon SDK or CLI - Amazon Key Management Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use ListGrants with an Amazon SDK or CLI

The following code examples show how to use ListGrants.

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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); } }
  • For API details, see ListGrants in Amazon SDK for .NET API Reference.

CLI
Amazon CLI

To view the grants on an Amazon KMS key

The following list-grants example displays all of the grants on the specified Amazon managed KMS key for Amazon DynamoDB in your account. This grant allows DynamoDB to use the KMS key on your behalf to encrypt a DynamoDB table before writing it to disk. You can use a command like this one to view the grants on the Amazon managed KMS keys and customer managed KMS keys in the Amazon account and Region.

This command uses the key-id parameter with a key ID to identify the KMS key. You can use a key ID or key ARN to identify the KMS key. To get the key ID or key ARN of an Amazon managed KMS key, use the list-keys or list-aliases command.

aws kms list-grants \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

The output shows that the grant gives Amazon DynamoDB permission to use the KMS key for cryptographic operations, and gives it permission to view details about the KMS key (DescribeKey) and to retire grants (RetireGrant). The EncryptionContextSubset constraint limits these permission to requests that include the specified encryption context pairs. As a result, the permissions in the grant are effective only on specified account and DynamoDB table.

{ "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" } ] }

For more information, see Grants in Amazon KMS in the Amazon Key Management Service Developer Guide.

  • For API details, see ListGrants in Amazon CLI Command Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/** * 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); } }); }
  • For API details, see ListGrants in Amazon SDK for Java 2.x API Reference.

Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

suspend fun displayGrantIds(keyIdVal: String?) { val request = ListGrantsRequest { keyId = keyIdVal limit = 15 } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.listGrants(request) response.grants?.forEach { grant -> println("The grant Id is ${grant.grantId}") } } }
  • For API details, see ListGrants in Amazon SDK for Kotlin API reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class GrantManager: def __init__(self, kms_client): self.kms_client = 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. """ answer = input(f"Ready to list grants on key {key_id} (y/n)? ") if answer.lower() == "y": try: grants = self.kms_client.list_grants(KeyId=key_id)["Grants"] except ClientError as err: logger.error( "Couldn't list grants for key %s. Here's why: %s", key_id, err.response["Error"]["Message"], ) else: print(f"Grants for key {key_id}:") pprint(grants) return grants
  • For API details, see ListGrants in Amazon SDK for Python (Boto3) API Reference.

For a complete list of Amazon SDK developer guides and code examples, see Using Amazon KMS with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.