将 ListKeyPolicies 与 AWS SDK 或 CLI 配合使用 - AWS Key Management Service

ListKeyPolicies 与 AWS SDK 或 CLI 配合使用

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

CLI
AWS CLI

获取 KMS 密钥的密钥策略名称

以下 list-key-policies 示例获取示例账户和区域中客户托管密钥的密钥策略名称。您可以使用此命令来查找有关 AWS 托管的密钥和客户托管密钥的密钥策略名称。

由于唯一有效的密钥策略名称是 default,因此,此命令没有用。

要指定 KMS 密钥,请使用 key-id 参数。此示例使用密钥 ID 值,但您可以在此命令中使用密钥 ID 或密钥 ARN。

aws kms list-key-policies \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

输出:

{ "PolicyNames": [ "default" ] }

有关 AWS KMS 密钥策略的更多信息,请参阅《AWS 密钥管理服务开发人员指南》中的在 AWS KMS 中使用密钥策略

  • 有关 API 详细信息,请参阅《AWS CLI 命令参考》中的 ListKeyPolicies

Java
适用于 Java 的 SDK 2.x
注意

查看 GitHub,了解更多信息。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/** * Asynchronously retrieves the key policy for the specified key ID and policy name. * * @param keyId the ID of the AWS KMS key for which to retrieve the policy * @param policyName the name of the key policy to retrieve * @return a {@link CompletableFuture} that, when completed, contains the key policy as a {@link String} */ public CompletableFuture<String> getKeyPolicyAsync(String keyId, String policyName) { GetKeyPolicyRequest policyRequest = GetKeyPolicyRequest.builder() .keyId(keyId) .policyName(policyName) .build(); return getAsyncClient().getKeyPolicy(policyRequest) .thenApply(response -> { String policy = response.policy(); logger.info("The response is: " + policy); return policy; }) .exceptionally(ex -> { throw new RuntimeException("Failed to get key policy", ex); }); }
  • 有关 API 的详细信息,请参阅《AWS SDK for Java 2.x API 参考》中的 ListKeyPolicies

Python
适用于 Python 的 SDK (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 list_policies(self, key_id): """ Lists the names of the policies for a key. :param key_id: The ARN or ID of the key to query. """ try: policy_names = self.kms_client.list_key_policies(KeyId=key_id)[ "PolicyNames" ] except ClientError as err: logging.error( "Couldn't list your policies. Here's why: %s", err.response["Error"]["Message"], ) raise else: print(f"The policies for key {key_id} are:") pprint(policy_names)
  • 有关 API 详细信息,请参阅《AWS SDK for Python (Boto3) API 参考》中的 ListKeyPolicies

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