与 AWS SDK或AssociateAddress一起使用 CLI - Amazon Elastic Compute Cloud

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或AssociateAddress一起使用 CLI

以下代码示例演示如何使用 AssociateAddress

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <summary> /// Associates an Elastic IP address with an instance. When this association is /// created, the Elastic IP's public IP address is immediately used as the public /// IP address of the associated instance. /// </summary> /// <param name="allocationId">The allocation Id of an Elastic IP address.</param> /// <param name="instanceId">The instance Id of the EC2 instance to /// associate the address with.</param> /// <returns>The association Id that represents /// the association of the Elastic IP address with an instance.</returns> public async Task<string> AssociateAddress(string allocationId, string instanceId) { try { var request = new AssociateAddressRequest { AllocationId = allocationId, InstanceId = instanceId }; var response = await _amazonEC2.AssociateAddressAsync(request); return response.AssociationId; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidInstanceId") { _logger.LogError( $"InstanceId is invalid, unable to associate address. {ec2Exception.Message}"); } throw; } catch (Exception ex) { _logger.LogError( $"An error occurred while associating the Elastic IP.: {ex.Message}"); throw; } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 AssociateAddress” 中的。

Bash
AWS CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

############################################################################### # function ec2_associate_address # # This function associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance. # # Parameters: # -a allocation_id - The allocation ID of the Elastic IP address to associate. # -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with. # # Returns: # 0 - If successful. # 1 - If it fails. # ############################################################################### function ec2_associate_address() { local allocation_id instance_id response # Function to display usage information function usage() { echo "function ec2_associate_address" echo "Associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance." echo " -a allocation_id - The allocation ID of the Elastic IP address to associate." echo " -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with." echo "" } # Parse the command-line arguments while getopts "a:i:h" option; do case "${option}" in a) allocation_id="${OPTARG}" ;; i) instance_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 if [[ -z "$instance_id" ]]; then errecho "ERROR: You must provide an instance ID with the -i parameter." return 1 fi # Associate the Elastic IP address response=$(aws ec2 associate-address \ --allocation-id "$allocation_id" \ --instance-id "$instance_id" \ --query "AssociationId" \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports associate-address operation failed." errecho "$response" return 1 } echo "$response" 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 }
C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

Aws::EC2::EC2Client ec2Client(clientConfiguration); //! Associate an Elastic IP address with an EC2 instance. /*! \param instanceId: An EC2 instance ID. \param allocationId: An Elastic IP allocation ID. \param[out] associationID: String to receive the association ID. \param clientConfiguration: AWS client configuration. \return bool: True if the address was associated with the instance; otherwise, false. */ bool AwsDoc::EC2::associateAddress(const Aws::String &instanceId, const Aws::String &allocationId, Aws::String &associationID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::AssociateAddressRequest request; request.SetInstanceId(instanceId); request.SetAllocationId(allocationId); Aws::EC2::Model::AssociateAddressOutcome outcome = ec2Client.AssociateAddress(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to associate address " << allocationId << " with instance " << instanceId << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully associated address " << allocationId << " with instance " << instanceId << std::endl; associationID = outcome.GetResult().GetAssociationId(); } return outcome.IsSuccess(); }
  • 有关API详细信息,请参阅 “AWS SDK for C++ API参考 AssociateAddress” 中的。

CLI
AWS CLI

在 EC2-Classic 中关联弹性 IP 地址

此示例将弹性 IP 地址与 EC2-Classic 中的实例相关联。如果命令成功,则不返回任何输出。

命令:

aws ec2 associate-address --instance-id i-07ffe74c7330ebf53 --public-ip 198.51.100.0

要将弹性 IP 地址关联到 EC2-VPC

此示例将弹性 IP 地址与中的实例相关联VPC。

命令:

aws ec2 associate-address --instance-id i-0b263919b6498b123 --allocation-id eipalloc-64d5890a

输出:

{ "AssociationId": "eipassoc-2bebb745" }

本示例将弹性 IP 地址与网络接口相关联。

命令:

aws ec2 associate-address --allocation-id eipalloc-64d5890a --network-interface-id eni-1a2b3c4d

本示例将弹性 IP 与和网络接口关联的私有 IP 地址相关联。

命令:

aws ec2 associate-address --allocation-id eipalloc-64d5890a --network-interface-id eni-1a2b3c4d --private-ip-address 10.0.0.85
Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/** * Associates an Elastic IP address with an EC2 instance asynchronously. * * @param instanceId the ID of the EC2 instance to associate the Elastic IP address with * @param allocationId the allocation ID of the Elastic IP address to associate * @return a {@link CompletableFuture} that completes with the association ID when the operation is successful, * or throws a {@link RuntimeException} if the operation fails */ public CompletableFuture<String> associateAddressAsync(String instanceId, String allocationId) { AssociateAddressRequest associateRequest = AssociateAddressRequest.builder() .instanceId(instanceId) .allocationId(allocationId) .build(); CompletableFuture<AssociateAddressResponse> responseFuture = getAsyncClient().associateAddress(associateRequest); return responseFuture.thenApply(response -> { if (response.associationId() != null) { return response.associationId(); } else { throw new RuntimeException("Association ID is null after associating address."); } }).whenComplete((result, ex) -> { if (ex != null) { throw new RuntimeException("Failed to associate address", ex); } }); }
  • 有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 AssociateAddress” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { AssociateAddressCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) * with an instance or a network interface. * @param {{ instanceId: string, allocationId: string }} options */ export const main = async ({ instanceId, allocationId }) => { const client = new EC2Client({}); const command = new AssociateAddressCommand({ // You need to allocate an Elastic IP address before associating it with an instance. // You can do that with the AllocateAddressCommand. AllocationId: allocationId, // You need to create an EC2 instance before an IP address can be associated with it. // You can do that with the RunInstancesCommand. InstanceId: instanceId, }); try { const { AssociationId } = await client.send(command); console.log( `Address with allocation ID ${allocationId} is now associated with instance ${instanceId}.`, `The association ID is ${AssociationId}.`, ); } catch (caught) { if ( caught instanceof Error && caught.name === "InvalidAllocationID.NotFound" ) { console.warn( `${caught.message}. Did you provide the ID of a valid Elastic IP address AllocationId?`, ); } else { throw caught; } } };
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 AssociateAddress” 中的。

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun associateAddressSc( instanceIdVal: String?, allocationIdVal: String?, ): String? { val associateRequest = AssociateAddressRequest { instanceId = instanceIdVal allocationId = allocationIdVal } Ec2Client { region = "us-west-2" }.use { ec2 -> val associateResponse = ec2.associateAddress(associateRequest) return associateResponse.associationId } }
  • 有关API详细信息,请参阅AssociateAddress中的 Kotlin AWS SDK API 参考

PowerShell
用于 PowerShell

示例 1:此示例将指定的弹性 IP 地址与中的指定实例相关联VPC。

C:\> Register-EC2Address -InstanceId i-12345678 -AllocationId eipalloc-12345678

输出:

eipassoc-12345678

示例 2:此示例将指定的弹性 IP 地址与 EC2-Classic 中的指定实例相关联。

C:\> Register-EC2Address -InstanceId i-12345678 -PublicIp 203.0.113.17
  • 有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考AssociateAddress中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 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 associate( self, allocation_id: str, instance_id: str ) -> Union[Dict[str, Any], None]: """ Associates an Elastic IP address with an instance. When this association is created, the Elastic IP's public IP address is immediately used as the public IP address of the associated instance. :param allocation_id: The allocation ID of the Elastic IP. :param instance_id: The ID of the Amazon EC2 instance. :return: A response that contains the ID of the association, or None if no Elastic IP is found. :raises ClientError: If the association fails, such as when the instance ID 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 None try: response = self.ec2_client.associate_address( AllocationId=allocation_id, InstanceId=instance_id ) elastic_ip.instance_id = ( instance_id # Track the instance associated with this Elastic IP. ) except ClientError as err: if err.response["Error"]["Code"] == "InvalidInstanceID.NotFound": logger.error( f"Failed to associate Elastic IP {allocation_id} with {instance_id} " "because the specified instance ID does not exist or has not propagated fully. " "Verify the instance ID and try again, or wait a few moments before attempting to " "associate the Elastic IP address." ) raise return response
  • 有关API详细信息,请参阅AssociateAddress中的 AWS SDKPython (Boto3) API 参考。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

# Associates an Elastic IP address with an Amazon Elastic Compute Cloud # (Amazon EC2) instance. # # Prerequisites: # # - The allocation ID corresponding to the Elastic IP address. # - The Amazon EC2 instance. # # @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. # @param instance_id [String] The ID of the instance. # @return [String] The assocation ID corresponding to the association of the # Elastic IP address to the instance. # @example # puts allocate_elastic_ip_address( # Aws::EC2::Client.new(region: 'us-west-2'), # 'eipalloc-04452e528a66279EX', # 'i-033c48ef067af3dEX') def associate_elastic_ip_address_with_instance( ec2_client, allocation_id, instance_id ) response = ec2_client.associate_address( allocation_id: allocation_id, instance_id: instance_id ) response.association_id rescue StandardError => e puts "Error associating Elastic IP address with instance: #{e.message}" 'Error' end
  • 有关API详细信息,请参阅 “AWS SDK for Ruby API参考 AssociateAddress” 中的。

Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn associate_ip_address( &self, allocation_id: &str, instance_id: &str, ) -> Result<AssociateAddressOutput, EC2Error> { let response = self .client .associate_address() .allocation_id(allocation_id) .instance_id(instance_id) .send() .await?; Ok(response) }
  • 有关API详细信息,请参见AssociateAddress中的 Rust AWS SDK API 参考

SAP ABAP
SDK对于 SAP ABAP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

TRY. oo_result = lo_ec2->associateaddress( " oo_result is returned for testing purposes. " iv_allocationid = iv_allocation_id iv_instanceid = iv_instance_id ). MESSAGE 'Associated an Elastic IP address with an EC2 instance.' 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详细信息,请参阅AssociateAddress中的AWS SDK以供SAPABAPAPI参考

有关 AWS SDK开发者指南和代码示例的完整列表,请参阅使用创建 Amazon EC2 资源 AWS SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。