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

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

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

DeleteKeyPair 搭配 a AWS SDK 或 CLI 使用

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

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

.NET
AWS SDK for .NET
注意

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

/// <summary> /// Delete an Amazon EC2 key pair. /// </summary> /// <param name="keyPairName">The name of the key pair to delete.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteKeyPair(string keyPairName) { try { await _amazonEC2.DeleteKeyPairAsync(new DeleteKeyPairRequest(keyPairName)).ConfigureAwait(false); return true; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound") { _logger.LogError($"KeyPair {keyPairName} does not exist and cannot be deleted. Please verify the key pair name and try again."); } return false; } catch (Exception ex) { Console.WriteLine($"Couldn't delete the key pair because: {ex.Message}"); return false; } } /// <summary> /// Delete the temporary file where the key pair information was saved. /// </summary> /// <param name="tempFileName">The path to the temporary file.</param> public void DeleteTempFile(string tempFileName) { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } }
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS SDK for .NET 參考中的 API

Bash
AWS CLI 使用 Bash 指令碼
注意

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

############################################################################### # function ec2_delete_keypair # # This function deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair. # # Parameters: # -n key_pair_name - A key pair name. # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_delete_keypair() { local key_pair_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_delete_keypair" echo "Deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair." echo " -n key_pair_name - A key pair name." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) key_pair_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$key_pair_name" ]]; then errecho "ERROR: You must provide a key pair name with the -n parameter." usage return 1 fi response=$(aws ec2 delete-key-pair \ --key-name "$key_pair_name") || { aws_cli_error_log ${?} errecho "ERROR: AWS reports delete-key-pair operation failed.$response" return 1 } return 0 }

此範例中使用的公用程式函數。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 DeleteKeyPair

C++
C++ 的 SDK
注意

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

//! Delete an Amazon Elastic Compute Cloud (Amazon EC2) instance key pair. /*! \param keyPairName: A name for a key pair. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::deleteKeyPair(const Aws::String &keyPairName, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DeleteKeyPairRequest request; request.SetKeyName(keyPairName); const Aws::EC2::Model::DeleteKeyPairOutcome outcome = ec2Client.DeleteKeyPair( request); if (!outcome.IsSuccess()) { std::cerr << "Failed to delete key pair " << keyPairName << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted key pair named " << keyPairName << std::endl; } return outcome.IsSuccess(); }
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS SDK for C++ 參考中的 API

CLI
AWS CLI

刪除金鑰對

下列delete-key-pair範例會刪除指定的金鑰對。

aws ec2 delete-key-pair \ --key-name my-key-pair

輸出:

{ "Return": true, "KeyPairId": "key-03c8d3aceb53b507" }

如需詳細資訊,請參閱 AWS 命令列介面使用者指南中的建立和刪除金鑰對

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

Java
Java 2.x 的 SDK
注意

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

/** * Deletes a key pair asynchronously. * * @param keyPair the name of the key pair to delete * @return a {@link CompletableFuture} that represents the result of the asynchronous operation. * The {@link CompletableFuture} will complete with a {@link DeleteKeyPairResponse} object * that provides the result of the key pair deletion operation. */ public CompletableFuture<DeleteKeyPairResponse> deleteKeysAsync(String keyPair) { DeleteKeyPairRequest request = DeleteKeyPairRequest.builder() .keyName(keyPair) .build(); // Initiate the asynchronous request to delete the key pair. CompletableFuture<DeleteKeyPairResponse> response = getAsyncClient().deleteKeyPair(request); return response.whenComplete((resp, ex) -> { if (ex != null) { throw new RuntimeException("Failed to delete key pair: " + keyPair, ex); } else if (resp == null) { throw new RuntimeException("No response received for deleting key pair: " + keyPair); } }); }
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS SDK for Java 2.x 參考中的 API

JavaScript
SDK for JavaScript (v3)
注意

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

import { DeleteKeyPairCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Deletes the specified key pair, by removing the public key from Amazon EC2. * @param {{ keyName: string }} options */ export const main = async ({ keyName }) => { const client = new EC2Client({}); const command = new DeleteKeyPairCommand({ KeyName: keyName, }); try { await client.send(command); console.log("Successfully deleted key pair."); } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide the required value?`); } else { throw caught; } } };
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS SDK for JavaScript 參考中的 API

Kotlin
Kotlin 的 SDK
注意

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

suspend fun deleteKeys(keyPair: String?) { val request = DeleteKeyPairRequest { keyName = keyPair } Ec2Client { region = "us-west-2" }.use { ec2 -> ec2.deleteKeyPair(request) println("Successfully deleted key pair named $keyPair") } }
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS for Kotlin SDK 參考中的 API

PowerShell
for PowerShell 工具

範例 1:此範例會刪除指定的金鑰對。除非您也指定強制參數,否則系統會提示您在操作進行之前進行確認。

Remove-EC2KeyPair -KeyName my-key-pair

輸出:

Confirm Are you sure you want to perform this action? Performing operation "Remove-EC2KeyPair (DeleteKeyPair)" on Target "my-key-pair". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 DeleteKeyPair

Python
Python 的 SDK (Boto3)
注意

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

class KeyPairWrapper: """ Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions. This class provides methods to create, list, and delete EC2 key pairs. """ def __init__( self, ec2_client: boto3.client, key_file_dir: Union[tempfile.TemporaryDirectory, str], key_pair: Optional[dict] = None, ): """ Initializes the KeyPairWrapper with the specified EC2 client, key file directory, and an optional key pair. :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level access to AWS EC2 services. :param key_file_dir: The folder where the private key information is stored. This should be a secure folder. :param key_pair: A dictionary representing the Boto3 KeyPair object. This is a high-level object that wraps key pair actions. Optional. """ self.ec2_client = ec2_client self.key_pair = key_pair self.key_file_path: Optional[str] = None self.key_file_dir = key_file_dir @classmethod def from_client(cls) -> "KeyPairWrapper": """ Class method to create an instance of KeyPairWrapper using a new EC2 client and a temporary directory for storing key files. :return: An instance of KeyPairWrapper. """ ec2_client = boto3.client("ec2") return cls(ec2_client, tempfile.TemporaryDirectory()) def delete(self, key_name: str) -> bool: """ Deletes a key pair by its name. :param key_name: The name of the key pair to delete. :return: A boolean indicating whether the deletion was successful. :raises ClientError: If there is an error in deleting the key pair, for example, if the key pair does not exist. """ try: self.ec2_client.delete_key_pair(KeyName=key_name) logger.info(f"Successfully deleted key pair: {key_name}") self.key_pair = None return True except self.ec2_client.exceptions.ClientError as err: logger.error(f"Deletion failed for key pair: {key_name}") error_code = err.response["Error"]["Code"] if error_code == "InvalidKeyPair.NotFound": logger.error( f"The key pair '{key_name}' does not exist and cannot be deleted. " "Please verify the key pair name and try again." ) raise
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS SDK for Python (Boto3) Word 參考中的 API

Rust
Rust 的 SDK
注意

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

繞著 delete_key 包裝,同時移除後端私有 PEM 金鑰。

pub async fn delete(self, ec2: &EC2, util: &Util) -> Result<(), EC2Error> { if let Some(key_name) = self.key_pair.key_name() { ec2.delete_key_pair(key_name).await?; if let Some(key_path) = self.key_file_path() { if let Err(err) = util.remove(key_path) { eprintln!("Failed to remove {key_path:?} ({err:?})"); } } } Ok(()) }
pub async fn delete_key_pair(&self, key_name: &str) -> Result<(), EC2Error> { let key_name: String = key_name.into(); tracing::info!("Deleting key pair {key_name}"); self.client .delete_key_pair() .key_name(key_name) .send() .await?; Ok(()) }
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair AWS for Rust SDK 參考中的 API

SAP ABAP
SDK for SAP ABAP
注意

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

TRY. lo_ec2->deletekeypair( iv_keyname = iv_key_name ). MESSAGE 'Amazon EC2 key pair deleted.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.
  • 如需 API 詳細資訊,請參閱 DeleteKeyPair for Word Word 參考中的 Word。 AWS SDK SAP ABAP API