Use AllocateAddress com um AWS SDK ou CLI - Amazon Elastic Compute Cloud

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use AllocateAddress com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o AllocateAddress.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

/// <summary> /// 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. /// </summary> /// <returns>The response object for the allocated address.</returns> public async Task<AllocateAddressResponse> AllocateAddress() { var request = new AllocateAddressRequest(); try { var response = await _amazonEC2.AllocateAddressAsync(request); Console.WriteLine($"Allocated IP: {response.PublicIp} with allocation ID {response.AllocationId}."); return response; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "AddressLimitExceeded") { // For more information on Elastic IP address quotas, see: // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-instance-addressing-limit _logger.LogError($"Unable to allocate Elastic IP, address limit exceeded. {ec2Exception.Message}"); } throw; } catch (Exception ex) { _logger.LogError($"An error occurred while allocating Elastic IP.: {ex.Message}"); throw; } }
  • Para API obter detalhes, consulte AllocateAddressem AWS SDK for .NET APIReferência.

Bash
AWS CLI com script Bash
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 }

As funções utilitárias usadas neste exemplo.

############################################################################### # 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 }
  • Para API obter detalhes, consulte AllocateAddressna Referência de AWS CLI Comandos.

C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; }
  • Para API obter detalhes, consulte AllocateAddressem AWS SDK for C++ APIReferência.

CLI
AWS CLI

Exemplo 1: alocar um endereço IP elástico do conjunto de endereços da Amazon

O exemplo allocate-address a seguir aloca um endereço IP elástico. A Amazon EC2 seleciona o endereço do pool de endereços da Amazon.

aws ec2 allocate-address

Saída:

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

Para obter mais informações, consulte Endereços IP elásticos no Guia EC2 do usuário da Amazon.

Exemplo 2: alocar um endereço IP elástico e associá-lo a um grupo de borda de rede

O exemplo allocate-address a seguir aloca um endereço IP elástico e o associa ao grupo de borda de rede especificado.

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

Saída:

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

Para obter mais informações, consulte Endereços IP elásticos no Guia EC2 do usuário da Amazon.

Exemplo 3: alocar um endereço IP elástico de um conjunto de endereços de sua propriedade

O exemplo allocate-address a seguir aloca um endereço IP elástico de um conjunto de endereços que você trouxe para a conta da Amazon Web Services. A Amazon EC2 seleciona o endereço do pool de endereços.

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

Saída:

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

Para obter mais informações, consulte Endereços IP elásticos no Guia EC2 do usuário da Amazon.

  • Para API obter detalhes, consulte AllocateAddressna Referência de AWS CLI Comandos.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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); } }); }
  • Para API obter detalhes, consulte AllocateAddressem AWS SDK for Java 2.x APIReferência.

JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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(); }
  • Para API obter detalhes, consulte AllocateAddressem AWS SDK for JavaScript APIReferência.

Kotlin
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 } }
  • Para API obter detalhes, consulte a AllocateAddressreferência AWS SDKdo Kotlin API.

PowerShell
Ferramentas para PowerShell

Exemplo 1: Este exemplo aloca um endereço IP elástico para usar com uma instância em a. VPC

New-EC2Address -Domain Vpc

Saída:

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

Exemplo 2: Este exemplo aloca um endereço IP elástico para usar com uma instância em EC2 -Classic.

New-EC2Address

Saída:

AllocationId Domain PublicIp ------------ ------ -------- standard 203.0.113.17
  • Para API obter detalhes, consulte AllocateAddressem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 allocate(self) -> "ElasticIpWrapper.ElasticIp": """ 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 ElasticIp object for the newly created Elastic IP address. :raises ClientError: If the allocation fails, such as reaching the maximum limit of Elastic IPs. """ try: response = self.ec2_client.allocate_address(Domain="vpc") elastic_ip = self.ElasticIp( allocation_id=response["AllocationId"], public_ip=response["PublicIp"] ) self.elastic_ips.append(elastic_ip) except ClientError as err: if err.response["Error"]["Code"] == "AddressLimitExceeded": logger.error( "Max IP's reached. Release unused addresses or contact AWS Support for an increase." ) raise err return elastic_ip
  • Para API obter detalhes, consulte a AllocateAddressReferência AWS SDK do Python (Boto3). API

Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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') response.allocation_id rescue StandardError => e puts "Error allocating Elastic IP address: #{e.message}" 'Error' end
  • Para API obter detalhes, consulte AllocateAddressem AWS SDK for Ruby APIReferência.

Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

pub async fn allocate_ip_address(&self) -> Result<AllocateAddressOutput, EC2Error> { self.client .allocate_address() .domain(DomainType::Vpc) .send() .await .map_err(EC2Error::from) }
  • Para API obter detalhes, consulte AllocateAddressa AWS SDKAPIreferência do Rust.

SAP ABAP
SDKpara SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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.

Para obter uma lista completa de guias do AWS SDK desenvolvedor e exemplos de código, consulteCrie EC2 recursos da Amazon usando um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre SDK versões anteriores.