MCPcopy Create free account
hub / github.com/awsdocs/aws-doc-sdk-examples / KeyPolicy

Class KeyPolicy

python/example_code/kms/key_policies.py:23–159  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21
22# snippet-start:[python.example_code.kms.KeyPolicy.decl]
23class KeyPolicy:
24 def __init__(self, kms_client):
25 self.kms_client = kms_client
26
27 @classmethod
28 def from_client(cls) -> "KeyPolicy":
29 """
30 Creates a KeyPolicy instance with a default KMS client.
31
32 :return: An instance of KeyPolicy initialized with the default KMS client.
33 """
34 kms_client = boto3.client("kms")
35 return cls(kms_client)
36
37 # snippet-end:[python.example_code.kms.KeyPolicy.decl]
38
39 # snippet-start:[python.example_code.kms.ListKeyPolicies]
40 def list_policies(self, key_id):
41 """
42 Lists the names of the policies for a key.
43
44 :param key_id: The ARN or ID of the key to query.
45 """
46 try:
47 policy_names = self.kms_client.list_key_policies(KeyId=key_id)[
48 "PolicyNames"
49 ]
50 except ClientError as err:
51 logging.error(
52 "Couldn't list your policies. Here's why: %s",
53 err.response["Error"]["Message"],
54 )
55 raise
56 else:
57 print(f"The policies for key {key_id} are:")
58 pprint(policy_names)
59
60 # snippet-end:[python.example_code.kms.ListKeyPolicies]
61
62 # snippet-start:[python.example_code.kms.GetKeyPolicy]
63 def get_policy(self, key_id: str) -> dict[str, str]:
64 """
65 Gets the policy of a key.
66
67 :param key_id: The ARN or ID of the key to query.
68 :return: The key policy as a dict.
69 """
70 if key_id != "":
71 try:
72 response = self.kms_client.get_key_policy(
73 KeyId=key_id,
74 )
75 policy = json.loads(response["Policy"])
76 except ClientError as err:
77 logger.error(
78 "Couldn't get policy for key %s. Here's why: %s",
79 key_id,
80 err.response["Error"]["Message"],

Callers 3

kms_scenario.pyFile · 0.90
__init__Method · 0.90
key_policiesFunction · 0.85

Calls

no outgoing calls

Tested by 1

__init__Method · 0.72