与 AWS SDK或PutKeyPolicy一起使用 CLI - AWS Key Management Service

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或PutKeyPolicy一起使用 CLI

以下代码示例演示如何使用 PutKeyPolicy

CLI
AWS CLI

更改密钥的密KMS钥策略

以下 put-key-policy 示例更改客户托管密钥的密钥策略。

首先,创建密钥策略并将其保存在本地JSON文件中。在本示例中,该文件为 key_policy.json。您也可以将密钥策略指定为 policy 参数的字符串值。

此密钥策略中的第一条声明允许 AWS 账户使用IAM策略来控制对KMS密钥的访问。第二条语句允许test-user用户在KMS密钥上运行describe-keylist-keys命令。

key_policy.json 的内容:

{ "Version" : "2012-10-17", "Id" : "key-default-1", "Statement" : [ { "Sid" : "Enable IAM User Permissions", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:root" }, "Action" : "kms:*", "Resource" : "*" }, { "Sid" : "Allow Use of Key", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:user/test-user" }, "Action" : [ "kms:DescribeKey", "kms:ListKeys" ], "Resource" : "*" } ] }

为了识别KMS密钥,此示例使用密钥 ID,但您也可以使用密钥ARN。为了指定密钥策略,该命令使用 policy 参数。为了表示策略位于文件中,它使用所需的 file:// 前缀。需要使用此前缀来识别所有受支持操作系统上的文件。最后,该命令使用值为 defaultpolicy-name 参数。如果未指定策略名称,则默认值为 default。唯一有效值为 default

aws kms put-key-policy \ --policy-name default \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --policy file://key_policy.json

此命令不生成任何输出。要验证命令是否有效,请使用 get-key-policy 命令。以下示例命令获取相同密钥的KMS密钥策略。值为 textoutput 参数返回一种易于读取的文本格式。

aws kms get-key-policy \ --policy-name default \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --output text

输出:

{ "Version" : "2012-10-17", "Id" : "key-default-1", "Statement" : [ { "Sid" : "Enable IAM User Permissions", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:root" }, "Action" : "kms:*", "Resource" : "*" }, { "Sid" : "Allow Use of Key", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:user/test-user" }, "Action" : [ "kms:Describe", "kms:List" ], "Resource" : "*" } ] }

有关更多信息,请参阅《AWS Key Management Service 开发人员指南》中的更改密钥策略

PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/*** * @param string $keyId * @param string $policy * @return void */ public function putKeyPolicy(string $keyId, string $policy) { try { $this->client->putKeyPolicy([ 'KeyId' => $keyId, 'Policy' => $policy, ]); }catch(KmsException $caught){ echo "There was a problem replacing the key policy: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
  • 有关API详细信息,请参阅 “AWS SDK for PHP API参考 PutKeyPolicy” 中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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 set_policy(self, key_id: str, policy: dict[str, any]) -> None: """ 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. :param policy: The existing policy of the key. :return: None """ principal = input( "Enter the ARN of an IAM role to set as the principal on the policy: " ) if key_id != "" and principal != "": # The updated policy replaces the existing policy. Add a new statement to # the list along with the original policy statements. policy["Statement"].append( { "Sid": "Allow access for ExampleRole", "Effect": "Allow", "Principal": {"AWS": principal}, "Action": [ "kms:Encrypt", "kms:GenerateDataKey*", "kms:Decrypt", "kms:DescribeKey", "kms:ReEncrypt*", ], "Resource": "*", } ) try: self.kms_client.put_key_policy(KeyId=key_id, Policy=json.dumps(policy)) except ClientError as err: logger.error( "Couldn't set policy for key %s. Here's why %s", key_id, err.response["Error"]["Message"], ) raise else: print(f"Set policy for key {key_id}.") else: print("Skipping set policy demo.")
  • 有关API详细信息,请参阅PutKeyPolicy中的 AWS SDKPython (Boto3) API 参考。

有关 AWS SDK开发者指南和代码示例的完整列表,请参阅将此服务与 AWS SDK 结合使用。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。