Use ReleaseAddress com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use ReleaseAddress com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o ReleaseAddress.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; } }
  • Para API obter detalhes, consulte ReleaseAddressem AWS SDK for .NET APIReferência.

Bash
AWS CLI com script Bash
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 }

As funções utilitárias usadas neste exemplo.

############################################################################### # 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 obter detalhes, consulte ReleaseAddressna Referência de AWS CLI Comandos.

C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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(); }
  • Para API obter detalhes, consulte ReleaseAddressem AWS SDK for C++ APIReferência.

CLI
AWS CLI

Para liberar um endereço IP elástico para EC2 -Classic

Este exemplo libera um endereço IP elástico para uso com instâncias em EC2 -Classic. Se o comando for bem-sucedido, nenhuma saída será retornada.

Comando:

aws ec2 release-address --public-ip 198.51.100.0

Para liberar um endereço IP elástico para EC2 - VPC

Este exemplo libera um endereço IP elástico para uso com instâncias em umVPC. Se o comando for bem-sucedido, nenhuma saída será retornada.

Comando:

aws ec2 release-address --allocation-id eipalloc-64d5890a
  • Para API obter detalhes, consulte ReleaseAddressna Referência de AWS CLI Comandos.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; }
  • Para API obter detalhes, consulte ReleaseAddressem AWS SDK for Java 2.x APIReferência.

JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; } } };
  • Para API obter detalhes, consulte ReleaseAddressem AWS SDK for JavaScript APIReferência.

Kotlin
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun releaseEC2AddressSc(allocId: String?) { val request = ReleaseAddressRequest { allocationId = allocId } Ec2Client { region = "us-west-2" }.use { ec2 -> ec2.releaseAddress(request) println("Successfully released Elastic IP address $allocId") } }
  • Para API obter detalhes, consulte a ReleaseAddressreferência AWS SDKdo Kotlin API.

PowerShell
Ferramentas para PowerShell

Exemplo 1: Este exemplo libera o endereço IP elástico especificado para instâncias em umVPC.

Remove-EC2Address -AllocationId eipalloc-12345678 -Force

Exemplo 2: Este exemplo libera o endereço IP elástico especificado para instâncias em EC2 -Classic.

Remove-EC2Address -PublicIp 198.51.100.2 -Force
  • Para API obter detalhes, consulte ReleaseAddressem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
  • Para API obter detalhes, consulte a ReleaseAddressReferência AWS SDK do Python (Boto3). API

Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
  • Para API obter detalhes, consulte ReleaseAddressem AWS SDK for Ruby APIReferência.

Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

pub async fn deallocate_ip_address(&self, allocation_id: &str) -> Result<(), EC2Error> { self.client .release_address() .allocation_id(allocation_id) .send() .await?; Ok(()) }
  • Para API obter detalhes, consulte ReleaseAddressa AWS SDKAPIreferência do Rust.

SAP ABAP
SDKpara SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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.