Utilícelo DeleteKeyPair con un o AWS SDK CLI - Ejemplos de código de AWS SDK

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Utilícelo DeleteKeyPair con un o AWS SDK CLI

En los siguientes ejemplos de código, se muestra cómo utilizar DeleteKeyPair.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 (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); } }
  • Para API obtener más información, consulte DeleteKeyPairla AWS SDK for .NET APIReferencia.

Bash
AWS CLI con el script Bash
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 }

Las funciones de utilidad utilizadas en este ejemplo.

############################################################################### # 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 }
  • Para API obtener más información, consulte DeleteKeyPairla Referencia de AWS CLI comandos.

C++
SDKpara C++
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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(); }
  • Para API obtener más información, consulte DeleteKeyPairla AWS SDK for C++ APIReferencia.

CLI
AWS CLI

Eliminar un par de claves

En el siguiente delete-key-pair ejemplo, se elimina el key pair especificado.

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

Salida:

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

Para obtener más información, consulte Crear y eliminar pares de claves en la Guía del usuario de la interfaz de línea de AWS comandos.

  • Para API obtener más información, consulte DeleteKeyPairla Referencia de AWS CLI comandos.

Java
SDKpara Java 2.x
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

public static void deleteKeys(Ec2Client ec2, String keyPair) { try { DeleteKeyPairRequest request = DeleteKeyPairRequest.builder() .keyName(keyPair) .build(); ec2.deleteKeyPair(request); System.out.println("Successfully deleted key pair named " + keyPair); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Para API obtener más información, consulte DeleteKeyPairla AWS SDK for Java 2.x APIReferencia.

JavaScript
SDKpara JavaScript (v3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import { DeleteKeyPairCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { const command = new DeleteKeyPairCommand({ KeyName: "KEY_PAIR_NAME", }); try { await client.send(command); console.log("Successfully deleted key pair."); } catch (err) { console.error(err); } };
  • Para API obtener más información, consulte DeleteKeyPairla AWS SDK for JavaScript APIReferencia.

Kotlin
SDKpara Kotlin
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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") } }
  • Para API obtener más información, consulta DeleteKeyPairla AWS SDKAPIreferencia sobre Kotlin.

PowerShell
Herramientas para PowerShell

Ejemplo 1: en este ejemplo se elimina el key pair especificado. Se le solicitará una confirmación antes de continuar con la operación, a menos que también especifique el parámetro Force.

Remove-EC2KeyPair -KeyName my-key-pair

Salida:

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"):
Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

class KeyPairWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.""" def __init__(self, ec2_resource, key_file_dir, key_pair=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param key_file_dir: The folder where the private key information is stored. This should be a secure folder. :param key_pair: A Boto3 KeyPair object. This is a high-level object that wraps key pair actions. """ self.ec2_resource = ec2_resource self.key_pair = key_pair self.key_file_path = None self.key_file_dir = key_file_dir @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource, tempfile.TemporaryDirectory()) def delete(self): """ Deletes a key pair. """ if self.key_pair is None: logger.info("No key pair to delete.") return key_name = self.key_pair.name try: self.key_pair.delete() self.key_pair = None except ClientError as err: logger.error( "Couldn't delete key %s. Here's why: %s : %s", key_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • Para API obtener más información, consulte DeleteKeyPairla AWS SDKreferencia de Python (Boto3). API

SAP ABAP
SDKpara SAP ABAP
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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.
  • Para API obtener más información, consulte DeleteKeyPairSAPABAPAPIcomo referencia.AWS SDK