Use CreateGrant 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 CreateGrant with an Amazon SDK or CLI

The following code examples show how to use CreateGrant.

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

public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); // The identity that is given permission to perform the operations // specified in the grant. var grantee = "arn:aws:iam::111122223333:role/ExampleRole"; // The identifier of the AWS KMS key to which the grant applies. You // can use the key ID or the Amazon Resource Name (ARN) of the KMS key. var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4"; var request = new CreateGrantRequest { GranteePrincipal = grantee, KeyId = keyId, // A list of operations that the grant allows. Operations = new List<string> { "Encrypt", "Decrypt", }, }; var response = await client.CreateGrantAsync(request); string grantId = response.GrantId; // The unique identifier of the grant. string grantToken = response.GrantToken; // The grant token. Console.WriteLine($"Id: {grantId}, Token: {grantToken}"); } }
  • For API details, see CreateGrant in Amazon SDK for .NET API Reference.

CLI
Amazon CLI

To create a grant

The following create-grant example creates a grant that allows the exampleUser user to use the decrypt command on the 1234abcd-12ab-34cd-56ef-1234567890ab example KMS key. The retiring principal is the adminRole role. The grant uses the EncryptionContextSubset grant constraint to allow this permission only when the encryption context in the decrypt request includes the "Department": "IT" key-value pair.

aws kms create-grant \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --grantee-principal arn:aws:iam::123456789012:user/exampleUser \ --operations Decrypt \ --constraints EncryptionContextSubset={Department=IT} \ --retiring-principal arn:aws:iam::123456789012:role/adminRole

Output:

{ "GrantId": "1a2b3c4d2f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2", "GrantToken": "<grant token here>" }

To view detailed information about the grant, use the list-grants command.

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

  • For API details, see CreateGrant 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.

/** * Grants permissions to a specified principal on a customer master key (CMK) asynchronously. * * @param keyId The unique identifier for the customer master key (CMK) that the grant applies to. * @param granteePrincipal The principal that is given permission to perform the operations that the grant permits on the CMK. * @return A {@link CompletableFuture} that, when completed, contains the ID of the created grant. * @throws RuntimeException If an error occurs during the grant creation process. */ public CompletableFuture<String> grantKeyAsync(String keyId, String granteePrincipal) { List<GrantOperation> grantPermissions = List.of( GrantOperation.ENCRYPT, GrantOperation.DECRYPT, GrantOperation.DESCRIBE_KEY ); CreateGrantRequest grantRequest = CreateGrantRequest.builder() .keyId(keyId) .name("grant1") .granteePrincipal(granteePrincipal) .operations(grantPermissions) .build(); CompletableFuture<CreateGrantResponse> responseFuture = getAsyncClient().createGrant(grantRequest); responseFuture.whenComplete((response, ex) -> { if (ex == null) { logger.info("Grant created successfully with ID: " + response.grantId()); } else { if (ex instanceof KmsException kmsEx) { throw new RuntimeException("Failed to create grant: " + kmsEx.getMessage(), kmsEx); } else { throw new RuntimeException("An unexpected error occurred: " + ex.getMessage(), ex); } } }); return responseFuture.thenApply(CreateGrantResponse::grantId); }
  • For API details, see CreateGrant 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 createNewGrant( keyIdVal: String?, granteePrincipalVal: String?, operation: String, ): String? { val operationOb = GrantOperation.fromValue(operation) val grantOperationList = ArrayList<GrantOperation>() grantOperationList.add(operationOb) val request = CreateGrantRequest { keyId = keyIdVal granteePrincipal = granteePrincipalVal operations = grantOperationList } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.createGrant(request) return response.grantId } }
  • For API details, see CreateGrant 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 create_grant(self, key_id): """ Creates a grant for a key that lets a principal generate a symmetric data encryption key. :param key_id: The ARN or ID of the key. :return: The grant that is created. """ principal = input( f"Enter the ARN of a principal, such as an IAM role, to grant that role " f"GenerateDataKey permissions on key {key_id}: " ) if principal != "": try: grant = self.kms_client.create_grant( KeyId=key_id, GranteePrincipal=principal, Operations=["GenerateDataKey"], ) except ClientError as err: logger.error( "Couldn't create a grant on key %s. Here's why: %s", key_id, err.response["Error"]["Message"], ) else: print(f"Grant created on key {key_id}.") return grant else: print("Skipping grant creation.")
  • For API details, see CreateGrant 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.