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

The following code examples show how to use GetKeyPolicy.

CLI
Amazon CLI

To copy a key policy from one KMS key to another KMS key

The following get-key-policy example gets the key policy from one KMS key and saves it in a text file. Then, it replaces the policy of a different KMS key using the text file as the policy input.

Because the --policy parameter of put-key-policy requires a string, you must use the --output text option to return the output as a text string instead of JSON.

aws kms get-key-policy \ --policy-name default \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --query Policy \ --output text > policy.txt aws kms put-key-policy \ --policy-name default \ --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --policy file://policy.txt

This command produces no output.

For more information, see PutKeyPolicy in the Amazon KMS API Reference.

  • For API details, see GetKeyPolicy in Amazon CLI Command 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 KeyPolicy: def __init__(self, kms_client): self.kms_client = kms_client def get_policy(self, key_id): """ Gets the policy of a key. :param key_id: The ARN or ID of the key to query. :return: The key policy as a dict. """ if key_id != "": try: response = self.kms_client.get_key_policy( KeyId=key_id, PolicyName="default" ) policy = json.loads(response["Policy"]) except ClientError as err: logger.error( "Couldn't get policy for key %s. Here's why: %s", key_id, err.response["Error"]["Message"], ) else: pprint(policy) return policy else: print("Skipping get policy demo.")
  • For API details, see GetKeyPolicy 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.