AWS SDK 또는 AssociateAddress CLI와 함께 사용 - Amazon Elastic Compute Cloud

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS SDK 또는 AssociateAddress CLI와 함께 사용

다음 코드 예제는 AssociateAddress의 사용 방법을 보여줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Associate an Elastic IP address to an EC2 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) { var request = new AssociateAddressRequest { AllocationId = allocationId, InstanceId = instanceId }; var response = await _amazonEC2.AssociateAddressAsync(request); return response.AssociationId; }
  • 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 }
  • API 세부 정보는 AWS CLI 명령 AssociateAddress참조를 참조하십시오.

C++
SDK for C++
참고

자세한 내용은 에서 확인할 수 GitHub 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::AssociateAddressRequest associate_request; associate_request.SetInstanceId(instanceId); associate_request.SetAllocationId(allocationId); const Aws::EC2::Model::AssociateAddressOutcome associate_outcome = ec2Client.AssociateAddress(associate_request); if (!associate_outcome.IsSuccess()) { std::cerr << "Failed to associate Elastic IP address " << allocationId << " with instance " << instanceId << ":" << associate_outcome.GetError().GetMessage() << std::endl; return false; } std::cout << "Successfully associated Elastic IP address " << allocationId << " with instance " << instanceId << std::endl;
  • 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

EC2-VPC에서 탄력적 IP 주소를 연결하는 방법

이 예제에서는 VPC의 인스턴스에 탄력적 IP 주소를 연결합니다.

명령:

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
  • API 세부 정보는 AWS CLI 명령 AssociateAddress참조를 참조하십시오.

Java
SDK for Java 2.x
참고

자세한 내용은 에서 확인할 수 GitHub 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

public static String associateAddress(Ec2Client ec2, String instanceId, String allocationId) { try { AssociateAddressRequest associateRequest = AssociateAddressRequest.builder() .instanceId(instanceId) .allocationId(allocationId) .build(); AssociateAddressResponse associateResponse = ec2.associateAddress(associateRequest); return associateResponse.associationId(); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
  • API 세부 정보는 AWS SDK for Java 2.x API AssociateAddress참조를 참조하십시오.

JavaScript
JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { AssociateAddressCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { // You need to allocate an Elastic IP address before associating it with an instance. // You can do that with the AllocateAddressCommand. const allocationId = "ALLOCATION_ID"; // You need to create an EC2 instance before an IP address can be associated with it. // You can do that with the RunInstancesCommand. const instanceId = "INSTANCE_ID"; const command = new AssociateAddressCommand({ AllocationId: allocationId, 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 (err) { console.error(err); } };
  • API 세부 정보는 AWS SDK for JavaScript API AssociateAddress참조를 참조하십시오.

Kotlin
SDK for 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 세부 정보는 Kotlin API용AWS SDK 레퍼런스를 참조하세요 AssociateAddress.

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 세부 정보는 Cmdlet 참조를 참조하십시오 AssociateAddress.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 associate(self, instance): """ 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 instance: A Boto3 Instance object. This is a high-level object that wraps Amazon EC2 instance actions. :return: A response that contains the ID of the association. """ if self.elastic_ip is None: logger.info("No Elastic IP to associate.") return try: response = self.elastic_ip.associate(InstanceId=instance.id) except ClientError as err: logger.error( "Couldn't associate Elastic IP %s with instance %s. Here's why: %s: %s", self.elastic_ip.allocation_id, instance.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise return response
  • API에 대한 자세한 내용은 파이썬용AWS SDK (Boto3) API 레퍼런스를 참조하십시오 AssociateAddress.

Ruby
SDK for 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, ) return response.association_id rescue StandardError => e puts "Error associating Elastic IP address with instance: #{e.message}" return "Error" end
  • API 세부 정보는 AWS SDK for Ruby API AssociateAddress참조를 참조하십시오.

SAP ABAP
SDK for 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 세부 정보는 SAP용AWS SDK ABAP API 참조를 참조하십시오 AssociateAddress.

AWS SDK 개발자 가이드 및 코드 예제의 전체 목록은 을 참조하십시오. SDK를 사용하여 Amazon EC2 리소스 생성 AWS 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.