AllocateAddressOR와 함께 사용 AWS SDK CLI - AWS SDK코드 예제

AWS 문서 AWS SDK SDK 예제 GitHub 리포지토리에 더 많은 예제가 있습니다.

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

AllocateAddressOR와 함께 사용 AWS SDK CLI

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

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

.NET
AWS SDK for .NET
참고

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

/// <summary> /// Allocate an Elastic IP address. /// </summary> /// <returns>The allocation Id of the allocated address.</returns> public async Task<string> AllocateAddress() { var request = new AllocateAddressRequest(); var response = await _amazonEC2.AllocateAddressAsync(request); return response.AllocationId; }
Bash
AWS CLI Bash 스크립트 사용
참고

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

############################################################################### # function ec2_allocate_address # # This function allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region. # # Parameters: # -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard'). # # Returns: # The allocated Elastic IP address, or an error message if the operation fails. # And: # 0 - If successful. # 1 - If it fails. # ############################################################################### function ec2_allocate_address() { local domain response # Function to display usage information function usage() { echo "function ec2_allocate_address" echo "Allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region." echo " -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard')." echo "" } # Parse the command-line arguments while getopts "d:h" option; do case "${option}" in d) domain="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 # Validate the input parameters if [[ -z "$domain" ]]; then errecho "ERROR: You must provide a domain with the -d parameter (either 'vpc' or 'standard')." return 1 fi if [[ "$domain" != "vpc" && "$domain" != "standard" ]]; then errecho "ERROR: Invalid domain value. Must be either 'vpc' or 'standard'." return 1 fi # Allocate the Elastic IP address response=$(aws ec2 allocate-address \ --domain "$domain" \ --query "[PublicIp,AllocationId]" \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports allocate-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 명령 AllocateAddress참조를 참조하십시오.

C++
SDKC++의 경우
참고

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

//! Allocate an Elastic IP address and associate it with an Amazon Elastic Compute Cloud //! (Amazon EC2) instance. /*! \param instanceID: An EC2 instance ID. \param[out] publicIPAddress: String to return the public IP address. \param[out] allocationID: String to return the allocation ID. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::allocateAndAssociateAddress(const Aws::String &instanceId, Aws::String &publicIPAddress, Aws::String &allocationID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::AllocateAddressRequest request; request.SetDomain(Aws::EC2::Model::DomainType::vpc); const Aws::EC2::Model::AllocateAddressOutcome outcome = ec2Client.AllocateAddress(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to allocate Elastic IP address:" << outcome.GetError().GetMessage() << std::endl; return false; } const Aws::EC2::Model::AllocateAddressResponse &response = outcome.GetResult(); allocationID = response.GetAllocationId(); publicIPAddress = response.GetPublicIp(); return true; }
CLI
AWS CLI

예제 1: Amazon 주소 풀에서 탄력적 IP 주소를 할당하는 방법

다음 allocate-address 예제는 탄력적 IP 주소를 할당합니다. Amazon은 Amazon의 주소 풀에서 주소를 EC2 선택합니다.

aws ec2 allocate-address

출력:

{ "PublicIp": "70.224.234.241", "AllocationId": "eipalloc-01435ba59eEXAMPLE", "PublicIpv4Pool": "amazon", "NetworkBorderGroup": "us-west-2", "Domain": "vpc" }

자세한 내용은 Amazon EC2 사용 설명서의 엘라스틱 IP 주소를 참조하십시오.

예제 2: 탄력적 IP 주소를 할당하고 네트워크 경계 그룹에 연결하는 방법

다음 allocate-address 예제에서는 탄력적 IP 주소를 할당하고 해당 주소를 지정된 네트워크 경계 그룹에 연결합니다.

aws ec2 allocate-address \ --network-border-group us-west-2-lax-1

출력:

{ "PublicIp": "70.224.234.241", "AllocationId": "eipalloc-e03dd489ceEXAMPLE", "PublicIpv4Pool": "amazon", "NetworkBorderGroup": "us-west-2-lax-1", "Domain": "vpc" }

자세한 내용은 Amazon EC2 사용 설명서의 엘라스틱 IP 주소를 참조하십시오.

예 3: 소유한 주소 풀에서 탄력적 IP 주소를 할당하는 방법

다음 allocate-address 예제에서는 Amazon Web Services 계정으로 가져온 주소 풀에서 탄력적 IP 주소를 할당합니다. Amazon은 주소 풀에서 주소를 EC2 선택합니다.

aws ec2 allocate-address \ --public-ipv4-pool ipv4pool-ec2-1234567890abcdef0

출력:

{ "AllocationId": "eipalloc-02463d08ceEXAMPLE", "NetworkBorderGroup": "us-west-2", "CustomerOwnedIp": "18.218.95.81", "CustomerOwnedIpv4Pool": "ipv4pool-ec2-1234567890abcdef0", "Domain": "vpc" "NetworkBorderGroup": "us-west-2", }

자세한 내용은 Amazon EC2 사용 설명서의 엘라스틱 IP 주소를 참조하십시오.

  • 자세한 API 내용은 AWS CLI 명령 AllocateAddress참조를 참조하십시오.

Java
SDK자바 2.x의 경우
참고

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

/** * Allocates an Elastic IP address asynchronously in the VPC domain. * * @return a {@link CompletableFuture} containing the allocation ID of the allocated Elastic IP address */ public CompletableFuture<String> allocateAddressAsync() { AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder() .domain(DomainType.VPC) .build(); CompletableFuture<AllocateAddressResponse> responseFuture = getAsyncClient().allocateAddress(allocateRequest); return responseFuture.thenApply(AllocateAddressResponse::allocationId).whenComplete((result, ex) -> { if (ex != null) { throw new RuntimeException("Failed to allocate address", ex); } }); }
JavaScript
SDK JavaScript (v3) 에 대한
참고

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

import { AllocateAddressCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Allocates an Elastic IP address to your AWS account. */ export const main = async () => { const client = new EC2Client({}); const command = new AllocateAddressCommand({}); try { const { AllocationId, PublicIp } = await client.send(command); console.log("A new IP address has been allocated to your account:"); console.log(`ID: ${AllocationId} Public IP: ${PublicIp}`); console.log( "You can view your IP addresses in the AWS Management Console for Amazon EC2. Look under Network & Security > Elastic IPs", ); } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide these values?`); } else { throw caught; } } }; import { fileURLToPath } from "url"; // Call function if run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); }
Kotlin
SDK코틀린의 경우
참고

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

suspend fun getAllocateAddress(instanceIdVal: String?): String? { val allocateRequest = AllocateAddressRequest { domain = DomainType.Vpc } Ec2Client { region = "us-west-2" }.use { ec2 -> val allocateResponse = ec2.allocateAddress(allocateRequest) val allocationIdVal = allocateResponse.allocationId val request = AssociateAddressRequest { instanceId = instanceIdVal allocationId = allocationIdVal } val associateResponse = ec2.associateAddress(request) return associateResponse.associationId } }
  • 자세한 API AWS SDK내용은 Kotlin API 참조를 참조하세요 AllocateAddress.

PowerShell
다음을 위한 도구 PowerShell

예 1: 이 예제는 a의 VPC 인스턴스에 사용할 엘라스틱 IP 주소를 할당합니다.

New-EC2Address -Domain Vpc

출력:

AllocationId Domain PublicIp ------------ ------ -------- eipalloc-12345678 vpc 198.51.100.2

예 2: 이 예제에서는 -Classic의 인스턴스에 사용할 엘라스틱 IP 주소를 할당합니다. EC2

New-EC2Address

출력:

AllocationId Domain PublicIp ------------ ------ -------- standard 203.0.113.17
  • 자세한 API 내용은 AWS Tools for PowerShell Cmdlet AllocateAddress참조를 참조하십시오.

Python
SDK파이썬용 (보토3)
참고

더 많은 정보가 있습니다. 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 allocate(self): """ Allocates an Elastic IP address that can be associated with an Amazon EC2 instance. By using an Elastic IP address, you can keep the public IP address constant even when you restart the associated instance. :return: The newly created Elastic IP object. By default, the address is not associated with any instance. """ try: response = self.ec2_resource.meta.client.allocate_address(Domain="vpc") self.elastic_ip = self.ec2_resource.VpcAddress(response["AllocationId"]) except ClientError as err: logger.error( "Couldn't allocate Elastic IP. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return self.elastic_ip
  • 자세한 API AWS SDK내용은 Python (Boto3) API 참조를 참조하십시오 AllocateAddress.

Ruby
SDK루비의 경우
참고

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

# Creates an Elastic IP address in Amazon Virtual Private Cloud (Amazon VPC). # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @return [String] The allocation ID corresponding to the Elastic IP address. # @example # puts allocate_elastic_ip_address(Aws::EC2::Client.new(region: 'us-west-2')) def allocate_elastic_ip_address(ec2_client) response = ec2_client.allocate_address(domain: "vpc") return response.allocation_id rescue StandardError => e puts "Error allocating Elastic IP address: #{e.message}" return "Error" end
Rust
SDKRust의 경우
참고

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

pub async fn allocate_ip_address(&self) -> Result<AllocateAddressOutput, EC2Error> { self.client .allocate_address() .domain(DomainType::Vpc) .send() .await .map_err(EC2Error::from) }
  • 자세한 API AWS SDK내용은 Rust API 참조를 참조하십시오 AllocateAddress.

SAP ABAP
SDK... 에 대한 SAP ABAP
참고

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

TRY. oo_result = lo_ec2->allocateaddress( iv_domain = 'vpc' ). " oo_result is returned for testing purposes. " MESSAGE 'Allocated an Elastic IP address.' 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 AWS SDK내용은 AllocateAddress에서 SAP ABAP API 참조를 참조하십시오.