搭DisassociateAddress配 AWS 開發套件或 CLI 使用 - Amazon Elastic Compute Cloud

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

DisassociateAddress配 AWS 開發套件或 CLI 使用

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

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

.NET
AWS SDK for .NET
注意

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

/// <summary> /// Disassociate an Elastic IP address from an EC2 instance. /// </summary> /// <param name="associationId">The association Id.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DisassociateIp(string associationId) { var response = await _amazonEC2.DisassociateAddressAsync( new DisassociateAddressRequest { AssociationId = associationId }); return response.HttpStatusCode == HttpStatusCode.OK; }
Bash
AWS CLI 與 Bash 腳本
注意

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

############################################################################### # function ec2_disassociate_address # # This function disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance. # # Parameters: # -a association_id - The association ID that represents the association of the Elastic IP address with an instance. # # And: # 0 - If successful. # 1 - If it fails. # ############################################################################### function ec2_disassociate_address() { local association_id response # Function to display usage information function usage() { echo "function ec2_disassociate_address" echo "Disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance." echo " -a association_id - The association ID that represents the association of the Elastic IP address with an instance." echo "" } # Parse the command-line arguments while getopts "a:h" option; do case "${option}" in a) association_id="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 # Validate the input parameters if [[ -z "$association_id" ]]; then errecho "ERROR: You must provide an association ID with the -a parameter." return 1 fi response=$(aws ec2 disassociate-address \ --association-id "$association_id") || { aws_cli_error_log ${?} errecho "ERROR: AWS reports disassociate-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 }
CLI
AWS CLI

在 EC2-Classic 中取消彈性 IP 地址的關聯

此範例會在 EC2-Classic 中取消彈性 IP 地址與執行個體的關聯。如果命令成功,則不會傳回任何輸出。

命令:

aws ec2 disassociate-address --public-ip 198.51.100.0

在 EC2-VPC 中取消彈性 IP 地址的關聯

此範例會在 VPC 中取消彈性 IP 地址與執行個體的關聯。如果命令成功,則不會傳回任何輸出。

命令:

aws ec2 disassociate-address --association-id eipassoc-2bebb745
Java
適用於 Java 2.x 的 SDK
注意

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

public static void disassociateAddress(Ec2Client ec2, String associationId) { try { DisassociateAddressRequest addressRequest = DisassociateAddressRequest.builder() .associationId(associationId) .build(); ec2.disassociateAddress(addressRequest); System.out.println("You successfully disassociated the address!"); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考DisassociateAddress中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

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

import { DisassociateAddressCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; // Disassociate an Elastic IP address from an instance. export const main = async () => { const command = new DisassociateAddressCommand({ // You can also use PublicIp, but that is for EC2 classic which is being retired. AssociationId: "ASSOCIATION_ID", }); try { await client.send(command); console.log("Successfully disassociated address"); } catch (err) { console.error(err); } };
  • 如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考DisassociateAddress中的。

Kotlin
適用於 Kotlin 的 SDK
注意

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

suspend fun disassociateAddressSc(associationIdVal: String?) { val addressRequest = DisassociateAddressRequest { associationId = associationIdVal } Ec2Client { region = "us-west-2" }.use { ec2 -> ec2.disassociateAddress(addressRequest) println("You successfully disassociated the address!") } }
  • 有關 API 的詳細信息,請參閱 AWS SDK DisassociateAddress中的 Kotlin API 參考。

PowerShell
適用的工具 PowerShell

範例 1:此範例會取消指定彈性 IP 位址與 VPC 中指定執行個體的關聯。

Unregister-EC2Address -AssociationId eipassoc-12345678

範例 2:此範例會取消 EC2-Classic 中指定彈性 IP 位址與指定執行個體的關聯。

Unregister-EC2Address -PublicIp 203.0.113.17
  • 如需 API 詳細資訊,請參閱AWS Tools for PowerShell 指令程DisassociateAddress式參考中的。

Python
適用於 Python (Boto3) 的 SDK
注意

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

class ElasticIpWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions.""" def __init__(self, ec2_resource, elastic_ip=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 elastic_ip: A Boto3 VpcAddress object. This is a high-level object that wraps Elastic IP actions. """ self.ec2_resource = ec2_resource self.elastic_ip = elastic_ip @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource) def disassociate(self): """ Removes an association between an Elastic IP address and an instance. When the association is removed, the instance is assigned a new public IP address. """ if self.elastic_ip is None: logger.info("No Elastic IP to disassociate.") return try: self.elastic_ip.association.delete() except ClientError as err: logger.error( "Couldn't disassociate Elastic IP %s from its instance. Here's why: %s: %s", self.elastic_ip.allocation_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • 如需 API 的詳細資訊,請參閱AWS 開發套件DisassociateAddress中的 Python (博托 3) API 參考。

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱使用 AWS 開發套件建立 Amazon EC2 資源。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。