または DisassociateAddress で を使用する AWS SDK CLI - AWS SDK コード例

AWS Doc SDK Examples GitHub リポジトリには他にも AWS SDK例があります。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

または DisassociateAddress で を使用する AWS SDK 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; }
  • API 詳細については、「 リファレンスDisassociateAddress」の「」を参照してください。 AWS SDK for .NET API

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 }
  • API 詳細については、「 コマンドリファレンスDisassociateAddress」の「」を参照してください。 AWS CLI

CLI
AWS CLI

EC2-Classic で Elastic IP アドレスの関連付けを解除するには

この例では、EC2-Classic のインスタンスから Elastic IP アドレスの関連付けを解除します。コマンドが成功した場合、出力は返りません。

コマンド:

aws ec2 disassociate-address --public-ip 198.51.100.0

EC2- で Elastic IP アドレスの関連付けを解除するにはVPC

この例では、 内のインスタンスから Elastic IP アドレスの関連付けを解除しますVPC。コマンドが成功した場合、出力は返りません。

コマンド:

aws ec2 disassociate-address --association-id eipassoc-2bebb745
  • API 詳細については、「 コマンドリファレンスDisassociateAddress」の「」を参照してください。 AWS CLI

Java
SDK for Java 2.x
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

/** * Disassociates an Elastic IP address from an instance asynchronously. * * @param associationId The ID of the association you want to disassociate. * @return a {@link CompletableFuture} representing the asynchronous operation of disassociating the address. The * {@link CompletableFuture} will complete with a {@link DisassociateAddressResponse} when the operation is * finished. * @throws RuntimeException if the disassociation of the address fails. */ public CompletableFuture<DisassociateAddressResponse> disassociateAddressAsync(String associationId) { Ec2AsyncClient ec2 = getAsyncClient(); DisassociateAddressRequest addressRequest = DisassociateAddressRequest.builder() .associationId(associationId) .build(); // Disassociate the address asynchronously. CompletableFuture<DisassociateAddressResponse> response = ec2.disassociateAddress(addressRequest); response.whenComplete((resp, ex) -> { if (ex != null) { throw new RuntimeException("Failed to disassociate address", ex); } }); return response; }
  • API 詳細については、「 リファレンスDisassociateAddress」の「」を参照してください。 AWS SDK for Java 2.x API

JavaScript
SDK の JavaScript (v3)
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

import { DisassociateAddressCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Disassociate an Elastic IP address from an instance. * @param {{ associationId: string }} options */ export const main = async ({ associationId }) => { const client = new EC2Client({}); const command = new DisassociateAddressCommand({ // You can also use PublicIp, but that is for EC2 classic which is being retired. AssociationId: associationId, }); try { await client.send(command); console.log("Successfully disassociated address"); } catch (caught) { if ( caught instanceof Error && caught.name === "InvalidAssociationID.NotFound" ) { console.warn(`${caught.message}.`); } else { throw caught; } } };
  • API 詳細については、「 リファレンスDisassociateAddress」の「」を参照してください。 AWS SDK for JavaScript API

Kotlin
SDK Kotlin 用
注記

については、「」を参照してください 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 詳細については、Kotlin リファレンス DisassociateAddressの「」の「」を参照してください。 AWS SDK API

PowerShell
のツール PowerShell

例 1: この例では、指定された Elastic IP アドレスと 内の指定されたインスタンスの関連付けを解除しますVPC。

Unregister-EC2Address -AssociationId eipassoc-12345678

例 2: この例では、-EC2Classic で指定されたインスタンスから指定された Elastic IP アドレスの関連付けを解除します。

Unregister-EC2Address -PublicIp 203.0.113.17
  • API 詳細については、「 コマンドレットリファレンスDisassociateAddress」の「」を参照してください。 AWS Tools for PowerShell

Python
SDK for Python (Boto3)
注記

については、「」を参照してください 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 詳細については、「 for Python (Boto3) リファレンスDisassociateAddress」の「」を参照してください。 AWS SDK API

Rust
SDK Rust 用
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

pub async fn disassociate_ip_address(&self, association_id: &str) -> Result<(), EC2Error> { self.client .disassociate_address() .association_id(association_id) .send() .await?; Ok(()) }
  • API 詳細については、AWS SDKRust APIリファレンスのDisassociateAddress「」の「」を参照してください。