Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
AWS SDK を使用して、Amazon EC2 の Elastic IP アドレスを割り当てる
以下のコード例は、Amazon EC2 に Elastic IP アドレスを割り当てる方法を示しています。
アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
- .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; }
-
API の詳細については、「 API リファレンスAllocateAddress」の「」を参照してください。 AWS SDK for .NET
-
- C++
-
- SDK for C++
-
注記
には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリ
での設定と実行の方法を確認してください。 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; } allocationId = outcome.GetResult().GetAllocationId();
-
API の詳細については、「 API リファレンスAllocateAddress」の「」を参照してください。 AWS SDK for C++
-
- CLI
-
- AWS CLI
-
例 1: Amazon のアドレスプールから Elastic IP アドレスを割り当てるには
次の
allocate-address
の例では、Elastic IP アドレスを割り当てています。Amazon EC2 は、Amazon のアドレスプールからアドレスを選択します。aws ec2 allocate-address
出力:
{ "PublicIp": "70.224.234.241", "AllocationId": "eipalloc-01435ba59eEXAMPLE", "PublicIpv4Pool": "amazon", "NetworkBorderGroup": "us-west-2", "Domain": "vpc" }
詳細については、「Amazon EC2 ユーザーガイド」の「Elastic IP アドレス」を参照してください。
例 2: Elastic IP アドレスを割り当て、インスタンスまたはネットワークボーダーグループと関連付けるには
次の
allocate-address
の例では、Elastic 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 ユーザーガイド」の「Elastic IP アドレス」を参照してください。
例 3: 所有するアドレスプールから Elastic IP アドレスを割り当てるには
次の
allocate-address
の例では、Amazon Web Services アカウントに入れたアドレスプールから Elastic 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 ユーザーガイド」の「Elastic IP アドレス」を参照してください。
-
API の詳細については、「 コマンドリファレンスAllocateAddress
」の「」を参照してください。 AWS CLI
-
- Java
-
- SDK for Java 2.x
-
注記
には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリ
での設定と実行の方法を確認してください。 import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.AllocateAddressRequest; import software.amazon.awssdk.services.ec2.model.DomainType; import software.amazon.awssdk.services.ec2.model.AllocateAddressResponse; import software.amazon.awssdk.services.ec2.model.AssociateAddressRequest; import software.amazon.awssdk.services.ec2.model.AssociateAddressResponse; import software.amazon.awssdk.services.ec2.model.Ec2Exception; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class AllocateAddress { public static void main(String[] args) { final String usage = """ Usage: <instanceId> Where: instanceId - An instance id value that you can obtain from the AWS Console.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String instanceId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() .region(region) .build(); System.out.println(getAllocateAddress(ec2, instanceId)); ec2.close(); } public static String getAllocateAddress(Ec2Client ec2, String instanceId) { try { AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder() .domain(DomainType.VPC) .build(); AllocateAddressResponse allocateResponse = ec2.allocateAddress(allocateRequest); String allocationId = allocateResponse.allocationId(); 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 の詳細については、「 API リファレンスAllocateAddress」の「」を参照してください。 AWS SDK for Java 2.x
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注記
には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリ
での設定と実行の方法を確認してください。 import { AllocateAddressCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { 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 (err) { console.error(err); } };
-
API の詳細については、「 API リファレンスAllocateAddress」の「」を参照してください。 AWS SDK for JavaScript
-
- Kotlin
-
- SDK for Kotlin
-
注記
には他にもがあります 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 の詳細については、AllocateAddress
AWS「 SDK for Kotlin API リファレンス」の「」を参照してください。
-
- 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 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 の詳細については、 AllocateAddress AWS SDK for Python (Boto3) API リファレンスの「」を参照してください。
-
- Ruby
-
- SDK for Ruby
-
注記
には他にもがあります 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
-
API の詳細については、「 API リファレンスAllocateAddress」の「」を参照してください。 AWS SDK for Ruby
-
- SAP ABAP
-
- SDK for 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 の詳細については、AllocateAddressAWS「 SDK for SAP ABAP API リファレンス」の「」を参照してください。
-