将 ListKeys
与 AWS SDK 或 CLI 配合使用
以下代码示例演示如何使用 ListKeys
。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- .NET
-
- AWS SDK for .NET
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 using System; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; /// <summary> /// List the AWS Key Managements Service (AWS KMS) keys for the AWS Region /// of the default user. To list keys in another AWS Region, supply the Region /// as a parameter to the client constructor. /// </summary> public class ListKeys { public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); var request = new ListKeysRequest(); var response = new ListKeysResponse(); do { response = await client.ListKeysAsync(request); response.Keys.ForEach(key => { Console.WriteLine($"ID: {key.KeyId}, {key.KeyArn}"); }); // Set the Marker property when response.Truncated is true // in order to get the next keys. request.Marker = response.NextMarker; } while (response.Truncated); } }
-
有关 API 详细信息,请参阅《AWS SDK for .NET API 参考》中的 ListKeys。
-
- CLI
-
- AWS CLI
-
获取账户和区域中的 KMS 密钥
以下
list-keys
示例获取账户和区域中的 KMS 密钥。此命令返回 AWS 托管密钥和客户托管密钥。aws kms list-keys
输出:
{ "Keys": [ { "KeyArn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab" }, { "KeyArn": "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321", "KeyId": "0987dcba-09fe-87dc-65ba-ab0987654321" }, { "KeyArn": "arn:aws:kms:us-east-2:111122223333:key/1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d", "KeyId": "1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d" } ] }
有关更多信息,请参阅《AWS Key Management Service 开发人员指南》中的查看密钥。
-
有关 API 详细信息,请参阅《AWS CLI 命令参考》中的 ListKeys
。
-
- Java
-
- SDK for Java 2.x
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import software.amazon.awssdk.services.kms.KmsAsyncClient; import software.amazon.awssdk.services.kms.model.ListKeysRequest; import software.amazon.awssdk.services.kms.paginators.ListKeysPublisher; import java.util.concurrent.CompletableFuture; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class HelloKMS { public static void main(String[] args) { listAllKeys(); } public static void listAllKeys() { KmsAsyncClient kmsAsyncClient = KmsAsyncClient.builder() .build(); ListKeysRequest listKeysRequest = ListKeysRequest.builder() .limit(15) .build(); /* * The `subscribe` method is required when using paginator methods in the AWS SDK * because paginator methods return an instance of a `ListKeysPublisher`, which is * based on a reactive stream. This allows asynchronous retrieval of paginated * results as they become available. By subscribing to the stream, we can process * each page of results as they are emitted. */ ListKeysPublisher keysPublisher = kmsAsyncClient.listKeysPaginator(listKeysRequest); CompletableFuture<Void> future = keysPublisher .subscribe(r -> r.keys().forEach(key -> System.out.println("The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId()))) .whenComplete((result, exception) -> { if (exception != null) { System.err.println("Error occurred: " + exception.getMessage()); } else { System.out.println("Successfully listed all keys."); } }); try { future.join(); } catch (Exception e) { System.err.println("Failed to list keys: " + e.getMessage()); } } }
-
有关 API 详细信息,请参阅《AWS SDK for Java 2.x API 参考》中的 ListKeys。
-
- Kotlin
-
- 适用于 Kotlin 的 SDK
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun listAllKeys() { val request = ListKeysRequest { limit = 15 } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.listKeys(request) response.keys?.forEach { key -> println("The key ARN is ${key.keyArn}") println("The key Id is ${key.keyId}") } } }
-
有关 API 详细信息,请参阅《AWS SDK for Kotlin API 参考》中的 ListKeys
。
-
- PHP
-
- 适用于 PHP 的 SDK
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 /*** * @return array */ public function listKeys() { try { $contents = []; $paginator = $this->client->getPaginator("ListKeys"); foreach($paginator as $result){ foreach ($result['Content'] as $object) { $contents[] = $object; } } return $contents; }catch(KmsException $caught){ echo "There was a problem listing the keys: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
-
有关 API 的详细信息,请参阅《AWS SDK for PHP API 参考》中的 ListKeys。
-
- Python
-
- SDK for Python (Boto3)
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 class KeyManager: def __init__(self, kms_client): self.kms_client = kms_client self.created_keys = [] @classmethod def from_client(cls) -> "KeyManager": """ Creates a KeyManager instance with a default KMS client. :return: An instance of KeyManager initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def list_keys(self): """ Lists the keys for the current account by using a paginator. """ try: page_size = 10 print("\nLet's list your keys.") key_paginator = self.kms_client.get_paginator("list_keys") for key_page in key_paginator.paginate(PaginationConfig={"PageSize": 10}): print(f"Here are {len(key_page['Keys'])} keys:") pprint(key_page["Keys"]) if key_page["Truncated"]: answer = input( f"Do you want to see the next {page_size} keys (y/n)? " ) if answer.lower() != "y": break else: print("That's all your keys!") except ClientError as err: logging.error( "Couldn't list your keys. Here's why: %s", err.response["Error"]["Message"], )
-
有关 API 详细信息,请参阅《AWS SDK for Python (Boto3) API 参考》中的 ListKeys。
-
- Rust
-
- 适用于 Rust 的 SDK
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 async fn show_keys(client: &Client) -> Result<(), Error> { let resp = client.list_keys().send().await?; let keys = resp.keys.unwrap_or_default(); let len = keys.len(); for key in keys { println!("Key ARN: {}", key.key_arn.as_deref().unwrap_or_default()); } println!(); println!("Found {} keys", len); Ok(()) }
-
有关 API 详细信息,请参阅《AWS SDK for Rust API 参考》中的 ListKeys
。
-
有关 AWS SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 AWS SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。