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

Method set_policy

python/example_code/kms/key_policies.py:92–135  ·  view source on GitHub ↗

Sets the policy of a key. Setting a policy entirely overwrites the existing policy, so care is taken to add a statement to the existing list of statements rather than simply writing a new policy. :param key_id: The ARN or ID of the key to set the policy to.

(self, key_id: str, policy: dict[str, any])

Source from the content-addressed store, hash-verified

90
91 # snippet-start:[python.example_code.kms.PutKeyPolicy]
92 def set_policy(self, key_id: str, policy: dict[str, any]) -> None:
93 """
94 Sets the policy of a key. Setting a policy entirely overwrites the existing
95 policy, so care is taken to add a statement to the existing list of statements
96 rather than simply writing a new policy.
97
98 :param key_id: The ARN or ID of the key to set the policy to.
99 :param policy: The existing policy of the key.
100 :return: None
101 """
102 principal = input(
103 "Enter the ARN of an IAM role to set as the principal on the policy: "
104 )
105 if key_id != "" and principal != "":
106 # The updated policy replaces the existing policy. Add a new statement to
107 # the list along with the original policy statements.
108 policy["Statement"].append(
109 {
110 "Sid": "Allow access for ExampleRole",
111 "Effect": "Allow",
112 "Principal": {"AWS": principal},
113 "Action": [
114 "kms:Encrypt",
115 "kms:GenerateDataKey*",
116 "kms:Decrypt",
117 "kms:DescribeKey",
118 "kms:ReEncrypt*",
119 ],
120 "Resource": "*",
121 }
122 )
123 try:
124 self.kms_client.put_key_policy(KeyId=key_id, Policy=json.dumps(policy))
125 except ClientError as err:
126 logger.error(
127 "Couldn't set policy for key %s. Here's why %s",
128 key_id,
129 err.response["Error"]["Message"],
130 )
131 raise
132 else:
133 print(f"Set policy for key {key_id}.")
134 else:
135 print("Skipping set policy demo.")
136
137 # snippet-end:[python.example_code.kms.PutKeyPolicy]
138

Callers 1

key_policiesFunction · 0.95

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected