使用 AWS SDK 为 Amazon EC2 分配弹性 IP 地址
以下代码示例显示了如何为 Amazon EC2 分配弹性 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 的详细信息,请参阅《AWS SDK for .NET API 参考》中的 AllocateAddress。
-
- C++
-
- 适用于 C++ 的 SDK
-
注意
在 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 的详细信息,请参阅《AWS SDK for C++ API 参考》中的 AllocateAddress。
-
- Java
-
- SDK for Java 2.x
-
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 的详细信息,请参阅《AWS SDK for Java 2.x API 参考》中的 AllocateAddress。
-
- 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 的详细信息,请参阅《AWS SDK for JavaScript API 参考》中的 AllocateAddress。
-
- 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 详细信息,请参阅《AWS SDK for Kotlin API 参考》中的 AllocateAddress
。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
注意
在 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 for Python(Boto3)API 参考》中的 AllocateAddress。
-
- 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 的详细信息,请参阅《AWS SDK for Ruby API 参考》中的 AllocateAddress。
-
- SAP ABAP
-
- 适用于 SAP ABAP 的 SDK
-
注意
在 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 for SAP ABAP API 参考》中的 AllocateAddress。
-
有关 AWS 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 Amazon EC2 与 AWS SDK 结合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。