Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Usare ReleaseAddress con un AWS SDK o CLI
I seguenti esempi di codice mostrano come usare ReleaseAddress.
Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nei seguenti esempi di codice:
- .NET
-
- SDK per .NET
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. /// <summary> /// Release an Elastic IP address. After the Elastic IP address is released, /// it can no longer be used. /// </summary> /// <param name="allocationId">The allocation Id of the Elastic IP address.</param> /// <returns>True if successful.</returns> public async Task<bool> ReleaseAddress(string allocationId) { try { var request = new ReleaseAddressRequest { AllocationId = allocationId }; var response = await _amazonEC2.ReleaseAddressAsync(request); return response.HttpStatusCode == HttpStatusCode.OK; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidAllocationID.NotFound") { _logger.LogError( $"AllocationId {allocationId} was not found. {ec2Exception.Message}"); } return false; } catch (Exception ex) { _logger.LogError( $"An error occurred while releasing the AllocationId {allocationId}.: {ex.Message}"); return false; } }-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS SDK per .NET Riferimento API.
-
- Bash
-
- AWS CLI con script Bash
-
Nota
C'è dell'altro GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. ############################################################################### # function ec2_release_address # # This function releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance. # # Parameters: # -a allocation_id - The allocation ID of the Elastic IP address to release. # # Returns: # 0 - If successful. # 1 - If it fails. # ############################################################################### function ec2_release_address() { local allocation_id response # Function to display usage information function usage() { echo "function ec2_release_address" echo "Releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance." echo " -a allocation_id - The allocation ID of the Elastic IP address to release." echo "" } # Parse the command-line arguments while getopts "a:h" option; do case "${option}" in a) allocation_id="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 # Validate the input parameters if [[ -z "$allocation_id" ]]; then errecho "ERROR: You must provide an allocation ID with the -a parameter." return 1 fi response=$(aws ec2 release-address \ --allocation-id "$allocation_id") || { aws_cli_error_log ${?} errecho "ERROR: AWS reports release-address operation failed." errecho "$response" return 1 } return 0 }Le funzioni di utilità utilizzate in questo esempio.
############################################################################### # 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 }-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS CLI Riferimento al comando.
-
- C++
-
- SDK per C++
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. //! Release an Elastic IP address. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::releaseAddress(const Aws::String &allocationID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2(clientConfiguration); Aws::EC2::Model::ReleaseAddressRequest request; request.SetAllocationId(allocationID); Aws::EC2::Model::ReleaseAddressOutcome outcome = ec2.ReleaseAddress(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to release Elastic IP address " << allocationID << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully released Elastic IP address " << allocationID << std::endl; } return outcome.IsSuccess(); }-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS SDK per C++ Riferimento API.
-
- CLI
-
- AWS CLI
-
Esempio 1: rilasciare un indirizzo IP elastico per EC2-Classic
Quanto segue
release-addressl'esempio rilascia un indirizzo IP elastico da utilizzare con istanze in EC2-Classic.aws ec2 release-address \ --public-ip198.51.100.0Questo comando non produce output.
Per ulteriori informazioni, vedere Rilascia un indirizzo IP elastico nel Guida per l'utente di Amazon EC2.
Esempio 2: rilasciare un indirizzo IP elastico per EC2-VPC
Quanto segue
release-addressL'esempio rilascia un indirizzo IP elastico da utilizzare con le istanze in un VPC.aws ec2 release-address \ --allocation-ideipalloc-64d5890aQuesto comando non produce output.
Per ulteriori informazioni, consulta Rilascia un indirizzo IP elastico nel Guida per l'utente di Amazon EC2.
-
Per i dettagli sull'API, vedi ReleaseAddress
nel AWS CLI Riferimento al comando.
-
- Java
-
- SDK per Java 2.x
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. /** * Releases an Elastic IP address asynchronously. * * @param allocId the allocation ID of the Elastic IP address to be released * @return a {@link CompletableFuture} representing the asynchronous operation of releasing the Elastic IP address */ public CompletableFuture<ReleaseAddressResponse> releaseEC2AddressAsync(String allocId) { ReleaseAddressRequest request = ReleaseAddressRequest.builder() .allocationId(allocId) .build(); CompletableFuture<ReleaseAddressResponse> response = getAsyncClient().releaseAddress(request); response.whenComplete((resp, ex) -> { if (ex != null) { throw new RuntimeException("Failed to release Elastic IP address", ex); } }); return response; }-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS SDK for Java 2.x Riferimento API.
-
- JavaScript
-
- SDK per JavaScript (v3)
-
Nota
C'è dell'altro GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. import { ReleaseAddressCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Release an Elastic IP address. * @param {{ allocationId: string }} options */ export const main = async ({ allocationId }) => { const client = new EC2Client({}); const command = new ReleaseAddressCommand({ // You can also use PublicIp, but that is for EC2 classic which is being retired. AllocationId: allocationId, }); try { await client.send(command); console.log("Successfully released address."); } catch (caught) { if ( caught instanceof Error && caught.name === "InvalidAllocationID.NotFound" ) { console.warn(`${caught.message}. Please provide a valid AllocationID.`); } else { throw caught; } } };-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS SDK per JavaScript Riferimento API.
-
- Kotlin
-
- SDK per Kotlin
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. suspend fun releaseEC2AddressSc(allocId: String?) { val request = ReleaseAddressRequest { allocationId = allocId } Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 -> ec2.releaseAddress(request) println("Successfully released Elastic IP address $allocId") } }-
Per i dettagli sull'API, vedi ReleaseAddress
nel AWS Riferimento all'API SDK per Kotlin.
-
- PowerShell
-
- Utensili per PowerShell V4
-
Esempio 1: questo esempio rilascia l’indirizzo IP elastico specificato per le istanze in un VPC.
Remove-EC2Address -AllocationId eipalloc-12345678 -ForceEsempio 2: questo esempio rilascia l'indirizzo IP elastico specificato per le istanze in EC2-Classic.
Remove-EC2Address -PublicIp 198.51.100.2 -Force-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS Strumenti per PowerShell Riferimento al cmdlet (V4).
-
- Utensili per PowerShell V5
-
Esempio 1: questo esempio rilascia l’indirizzo IP elastico specificato per le istanze in un VPC.
Remove-EC2Address -AllocationId eipalloc-12345678 -ForceEsempio 2: questo esempio rilascia l'indirizzo IP elastico specificato per le istanze in EC2-Classic.
Remove-EC2Address -PublicIp 198.51.100.2 -Force-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS Strumenti per PowerShell Riferimento al cmdlet (V5).
-
- Python
-
- SDK for Python (Boto3)
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. class ElasticIpWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface.""" class ElasticIp: """Represents an Elastic IP and its associated instance.""" def __init__( self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None ) -> None: """ Initializes the ElasticIp object. :param allocation_id: The allocation ID of the Elastic IP. :param public_ip: The public IP address of the Elastic IP. :param instance_id: The ID of the associated EC2 instance, if any. """ self.allocation_id = allocation_id self.public_ip = public_ip self.instance_id = instance_id def __init__(self, ec2_client: Any) -> None: """ Initializes the ElasticIpWrapper with an EC2 client. :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level access to AWS EC2 services. """ self.ec2_client = ec2_client self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = [] @classmethod def from_client(cls) -> "ElasticIpWrapper": """ Creates an ElasticIpWrapper instance with a default EC2 client. :return: An instance of ElasticIpWrapper initialized with the default EC2 client. """ ec2_client = boto3.client("ec2") return cls(ec2_client) def release(self, allocation_id: str) -> None: """ Releases an Elastic IP address. After the Elastic IP address is released, it can no longer be used. :param allocation_id: The allocation ID of the Elastic IP to release. :raises ClientError: If the release fails, such as when the Elastic IP address is not found. """ elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id) if elastic_ip is None: logger.info(f"No Elastic IP found with allocation ID {allocation_id}.") return try: self.ec2_client.release_address(AllocationId=allocation_id) self.elastic_ips.remove(elastic_ip) # Remove the Elastic IP from the list except ClientError as err: if err.response["Error"]["Code"] == "InvalidAddress.NotFound": logger.error( f"Failed to release Elastic IP address {allocation_id} " "because it could not be found. Verify the Elastic IP address " "and ensure it is allocated to your account in the correct region " "before attempting to release it." ) raise-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS Riferimento alle API SDK per Python (Boto3).
-
- Ruby
-
- SDK per Ruby
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. # Releases an Elastic IP address from an # Amazon Elastic Compute Cloud (Amazon EC2) instance. # # Prerequisites: # # - An Amazon EC2 instance with an associated Elastic IP address. # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param allocation_id [String] The ID of the allocation corresponding to # the Elastic IP address. # @return [Boolean] true if the Elastic IP address was released; # otherwise, false. # @example # exit 1 unless elastic_ip_address_released?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'eipalloc-04452e528a66279EX' # ) def elastic_ip_address_released?(ec2_client, allocation_id) ec2_client.release_address(allocation_id: allocation_id) true rescue StandardError => e puts("Error releasing Elastic IP address: #{e.message}") false end-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS SDK per Ruby Riferimento API.
-
- Rust
-
- SDK per Rust
-
Nota
C'è altro su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. pub async fn deallocate_ip_address(&self, allocation_id: &str) -> Result<(), EC2Error> { self.client .release_address() .allocation_id(allocation_id) .send() .await?; Ok(()) }-
Per i dettagli sull'API, vedi ReleaseAddress
nel AWS SDK per Rust API di riferimento.
-
- SAP ABAP
-
- SDK per SAP ABAP
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. TRY. lo_ec2->releaseaddress( iv_allocationid = iv_allocation_id ). MESSAGE 'Elastic IP address released.' 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.-
Per i dettagli sull'API, vedi ReleaseAddress nel AWS Riferimento all'API SDK per SAP ABAP.
-
- Swift
-
- SDK per Swift
-
Nota
C'è altro su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. import AWSEC2 /// Release an allocated Elastic IP. /// /// - Parameter allocationId: The allocation ID of the Elastic IP to /// release. func releaseAddress(allocationId: String?) async { do { _ = try await ec2Client.releaseAddress( input: ReleaseAddressInput( allocationId: allocationId ) ) } catch { print("*** Unable to release the IP address: \(error.localizedDescription)") } }-
Per i dettagli sull'API, vedi ReleaseAddress
nel AWS Riferimento SDK per Swift API.
-
Per un elenco completo di AWS Guide per sviluppatori SDK ed esempi di codice, consulta Crea EC2 risorse Amazon utilizzando un AWS SDK. Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.