CreateAlias 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateAlias 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 CreateAlias

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

using System; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; /// <summary> /// Creates an alias for an AWS Key Management Service (AWS KMS) key. /// </summary> public class CreateAlias { public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); // The alias name must start with alias/ and can be // up to 256 alphanumeric characters long. var aliasName = "alias/ExampleAlias"; // The value supplied as the TargetKeyId can be either // the key ID or key Amazon Resource Name (ARN) of the // AWS KMS key. var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab"; var request = new CreateAliasRequest { AliasName = aliasName, TargetKeyId = keyId, }; var response = await client.CreateAliasAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Alias, {aliasName}, successfully created."); } else { Console.WriteLine($"Could not create alias."); } } }
  • 如需 API 詳細資訊,請參閱 CreateAlias AWS SDK for .NET 參考中的 API

CLI
AWS CLI

為 KMS 金鑰建立別名

下列create-alias命令會為金鑰 ID 所識別的 KMS 金鑰建立名為 example-alias的別名1234abcd-12ab-34cd-56ef-1234567890ab

別名名稱必須以 開頭alias/。請勿使用以 開頭的別名;alias/aws這些名稱會保留供 使用 AWS。

aws kms create-alias \ --alias-name alias/example-alias \ --target-key-id 1234abcd-12ab-34cd-56ef-1234567890ab

此命令不會傳回任何輸出。若要查看新的別名,請使用 list-aliases命令。

如需詳細資訊,請參閱 AWS Key Management Service 開發人員指南中的使用別名

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 CreateAlias

Java
Java 2.x 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Creates a custom alias for the specified target key asynchronously. * * @param targetKeyId the ID of the target key for the alias * @param aliasName the name of the alias to create * @return a {@link CompletableFuture} that completes when the alias creation operation is finished */ public CompletableFuture<Void> createCustomAliasAsync(String targetKeyId, String aliasName) { CreateAliasRequest aliasRequest = CreateAliasRequest.builder() .aliasName(aliasName) .targetKeyId(targetKeyId) .build(); CompletableFuture<CreateAliasResponse> responseFuture = getAsyncClient().createAlias(aliasRequest); responseFuture.whenComplete((response, exception) -> { if (exception == null) { logger.info("{} was successfully created.", aliasName); } else { if (exception instanceof ResourceExistsException) { logger.info("Alias [{}] already exists. Moving on...", aliasName); } else if (exception instanceof KmsException kmsEx) { throw new RuntimeException("KMS error occurred while creating alias: " + kmsEx.getMessage(), kmsEx); } else { throw new RuntimeException("An unexpected error occurred while creating alias: " + exception.getMessage(), exception); } } }); return responseFuture.thenApply(response -> null); }
  • 如需 API 詳細資訊,請參閱 CreateAlias AWS SDK for Java 2.x 參考中的 API

Kotlin
Kotlin 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createCustomAlias( targetKeyIdVal: String?, aliasNameVal: String?, ) { val request = CreateAliasRequest { aliasName = aliasNameVal targetKeyId = targetKeyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> kmsClient.createAlias(request) println("$aliasNameVal was successfully created") } }
  • 如需 API 詳細資訊,請參閱 CreateAlias AWS for Kotlin SDK 參考中的 API

PHP
適用於 PHP 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/*** * @param string $keyId * @param string $alias * @return void */ public function createAlias(string $keyId, string $alias) { try{ $this->client->createAlias([ 'TargetKeyId' => $keyId, 'AliasName' => $alias, ]); }catch (KmsException $caught){ if($caught->getAwsErrorMessage() == "InvalidAliasNameException"){ echo "The request was rejected because the specified alias name is not valid."; } throw $caught; } }
  • 如需 API 詳細資訊,請參閱 CreateAlias AWS SDK for PHP 參考中的 API

Python
SDK for Python (Boto3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class AliasManager: def __init__(self, kms_client): self.kms_client = kms_client self.created_key = None @classmethod def from_client(cls) -> "AliasManager": """ Creates an AliasManager instance with a default KMS client. :return: An instance of AliasManager initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def create_alias(self, key_id: str, alias: str) -> None: """ Creates an alias for the specified key. :param key_id: The ARN or ID of a key to give an alias. :param alias: The alias to assign to the key. """ try: self.kms_client.create_alias(AliasName=alias, TargetKeyId=key_id) except ClientError as err: if err.response["Error"]["Code"] == "AlreadyExistsException": logger.error( "Could not create the alias %s because it already exists.", key_id ) else: logger.error( "Couldn't encrypt text. Here's why: %s", err.response["Error"]["Message"], ) raise
  • 如需 API 詳細資訊,請參閱 CreateAlias AWS SDK for Python (Boto3) Word 參考中的 API