Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
与 Amazon SDK或GetKeyPolicy
一起使用 CLI
以下代码示例演示如何使用 GetKeyPolicy
。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- CLI
-
- Amazon CLI
-
将密钥策略从一个密KMS钥复制到另一个KMS密钥
以下get-key-policy
示例从一个密钥中获取KMS密钥策略并将其保存在文本文件中。然后,它使用文本文件作为策略输入替换另一个KMS密钥的策略。
由于的--policy
参数put-key-policy
需要字符串,因此必须使用--output text
选项将输出作为文本字符串返回,而不是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
此命令不生成任何输出。
有关更多信息,请参阅 “Amazon KMSAPI参考” PutKeyPolicy中的。
- Python
-
- SDK适用于 Python (Boto3)
-
class KeyPolicy:
def __init__(self, kms_client):
self.kms_client = kms_client
@classmethod
def from_client(cls) -> "KeyPolicy":
"""
Creates a KeyPolicy instance with a default KMS client.
:return: An instance of KeyPolicy initialized with the default KMS client.
"""
kms_client = boto3.client("kms")
return cls(kms_client)
def get_policy(self, key_id: str) -> dict[str, str]:
"""
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,
)
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"],
)
raise
else:
pprint(policy)
return policy
else:
print("Skipping get policy demo.")
有关 Amazon SDK开发者指南和代码示例的完整列表,请参阅将此服务与 Amazon SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。