文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
ReleaseAddress
搭配 a AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 ReleaseAddress
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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; } }
-
如需 API 詳細資訊,請參閱 ReleaseAddress AWS SDK for .NET 參考中的 API。
-
- Bash
-
- AWS CLI 使用 Bash 指令碼
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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 }
此範例中使用的公用程式函數。
############################################################################### # 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 命令參考中的 ReleaseAddress。
-
- C++
-
- C++ 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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(); }
-
如需 API 詳細資訊,請參閱 ReleaseAddress AWS SDK for C++ 參考中的 API。
-
- CLI
-
- AWS CLI
-
若要釋出 EC2-Classic 的彈性 IP 地址
此範例會釋出彈性 IP 地址,以搭配 EC2-Classic 中的執行個體使用。如果命令成功,則不會傳回任何輸出。
命令:
aws ec2 release-address --public-ip
198.51.100.0
若要釋出 EC2-VPC 的彈性 IP 地址
此範例會釋出彈性 IP 地址,以便與 VPC 中的執行個體搭配使用。如果命令成功,則不會傳回任何輸出。
命令:
aws ec2 release-address --allocation-id
eipalloc-64d5890a
-
如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 ReleaseAddress
。
-
- Java
-
- Java 2.x 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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; }
-
如需 API 詳細資訊,請參閱 ReleaseAddress AWS SDK for Java 2.x 參考中的 API。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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; } } };
-
如需 API 詳細資訊,請參閱 ReleaseAddress AWS SDK for JavaScript 參考中的 API。
-
- Kotlin
-
- Kotlin 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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") } }
-
如需 API 詳細資訊,請參閱 ReleaseAddress
AWS for Kotlin SDK 參考中的 API。
-
- PowerShell
-
- for PowerShell 工具
-
範例 1:此範例會發行 VPC 中執行個體的指定彈性 IP 地址。
Remove-EC2Address -AllocationId eipalloc-12345678 -Force
範例 2:此範例會發行 EC2-Classic 中執行個體的指定彈性 IP 地址。
Remove-EC2Address -PublicIp 198.51.100.2 -Force
-
如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 ReleaseAddress。
-
- Python
-
- SDK for Python (Boto3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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
-
如需 API 詳細資訊,請參閱 ReleaseAddress AWS SDK for Python (Boto3) Word 參考中的 API。
-
- Ruby
-
- Ruby 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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
-
如需 API 詳細資訊,請參閱 ReleaseAddress AWS SDK for Ruby 參考中的 API。
-
- Rust
-
- Rust 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 pub async fn deallocate_ip_address(&self, allocation_id: &str) -> Result<(), EC2Error> { self.client .release_address() .allocation_id(allocation_id) .send() .await?; Ok(()) }
-
如需 API 詳細資訊,請參閱 ReleaseAddress
AWS for Rust SDK 參考中的 API。
-
- SAP ABAP
-
- SDK for SAP ABAP
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 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.
-
如需 API 詳細資訊,請參閱 ReleaseAddress for Word Word 參考中的 Word。 AWS SDK SAP ABAP API
-