Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Usare CreateVpc con un AWS SDK o CLI
I seguenti esempi di codice mostrano come usare CreateVpc.
Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nei seguenti esempi di codice:
- CLI
-
- AWS CLI
-
Esempio 1: come creare un VPC
Nell’esempio di
create-vpcseguente viene creato un VPC con l’intervallo CIDR IPv4 specificato e un tag Nome.aws ec2 create-vpc \ --cidr-block10.0.0.0/16\ --tag-specificationsResourceType=vpc,Tags=[{Key=Name,Value=MyVpc}]Output:
{ "Vpc": { "CidrBlock": "10.0.0.0/16", "DhcpOptionsId": "dopt-5EXAMPLE", "State": "pending", "VpcId": "vpc-0a60eb65b4EXAMPLE", "OwnerId": "123456789012", "InstanceTenancy": "default", "Ipv6CidrBlockAssociationSet": [], "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-07501b79ecEXAMPLE", "CidrBlock": "10.0.0.0/16", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false, "Tags": [ { "Key": "Name", "Value": "MyVpc" } ] } }Esempio 2: come creare un VPC con tenancy dedicata
Nell’esempio di
create-vpcseguente viene creato un VPC con l’intervallo CIDR IPv4 specificato e una tenancy dedicata.aws ec2 create-vpc \ --cidr-block10.0.0.0/16\ --instance-tenancydedicatedOutput:
{ "Vpc": { "CidrBlock": "10.0.0.0/16", "DhcpOptionsId": "dopt-19edf471", "State": "pending", "VpcId": "vpc-0a53287fa4EXAMPLE", "OwnerId": "123456789012", "InstanceTenancy": "dedicated", "Ipv6CidrBlockAssociationSet": [], "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-00b24cc1c2EXAMPLE", "CidrBlock": "10.0.0.0/16", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false } }Esempio 3: come creare un VPC con un intervallo CIDR IPv6
Quanto segue
create-vpcl'esempio crea un VPC con un Amazon-provided Blocco CIDR IPv6.aws ec2 create-vpc \ --cidr-block10.0.0.0/16\ --amazon-provided-ipv6-cidr-blockOutput:
{ "Vpc": { "CidrBlock": "10.0.0.0/16", "DhcpOptionsId": "dopt-dEXAMPLE", "State": "pending", "VpcId": "vpc-0fc5e3406bEXAMPLE", "OwnerId": "123456789012", "InstanceTenancy": "default", "Ipv6CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-068432c60bEXAMPLE", "Ipv6CidrBlock": "", "Ipv6CidrBlockState": { "State": "associating" }, "Ipv6Pool": "Amazon", "NetworkBorderGroup": "us-west-2" } ], "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-0669f8f9f5EXAMPLE", "CidrBlock": "10.0.0.0/16", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false } }Esempio 4: come creare un VPC con un CIDR di un pool IPAM
Nell’esempio di
create-vpcseguente viene creato un VPC con un CIDR di un pool di Gestione indirizzi IP (IPAM) di Amazon VPC.Per Linux e macOS, usa il seguente comando.
aws ec2 create-vpc \ --ipv4-ipam-pool-idipam-pool-0533048da7d823723\ --tag-specifications ResourceType=vpc,Tags='[{Key=Environment,Value="Preprod"},{Key=Owner,Value="Build Team"}]'Per Windows, usa il seguente comando.
aws ec2 create-vpc^--ipv4-ipam-pool-idipam-pool-0533048da7d823723^--tag-specifications ResourceType=vpc,Tags=[{Key=Environment,Value="Preprod"},{Key=Owner,Value="Build Team"}]Output:
{ "Vpc": { "CidrBlock": "10.0.1.0/24", "DhcpOptionsId": "dopt-2afccf50", "State": "pending", "VpcId": "vpc-010e1791024eb0af9", "OwnerId": "123456789012", "InstanceTenancy": "default", "Ipv6CidrBlockAssociationSet": [], "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-0a77de1d803226d4b", "CidrBlock": "10.0.1.0/24", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false, "Tags": [ { "Key": "Environment", "Value": "Preprod" }, { "Key": "Owner", "Value": "Build Team" } ] } }Per ulteriori informazioni, consulta Creare un VPC che utilizza un CIDR del pool IPAM nella Guida per l’utente di Amazon VPC IPAM.
-
Per informazioni dettagliate sull'API, vedi CreateVpc
nel AWS CLI Riferimento al comando.
-
- PHP
-
- SDK per PHP
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. /** * @param string $cidr * @return array */ public function createVpc(string $cidr): array { try { $result = $this->ec2Client->createVpc([ "CidrBlock" => $cidr, ]); return $result['Vpc']; }catch(Ec2Exception $caught){ echo "There was a problem creating the VPC: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }-
Per i dettagli sull'API, vedi CreateVpc nel AWS SDK per PHP Riferimento API.
-
- PowerShell
-
- Utensili per PowerShell V4
-
Esempio 1: questo esempio crea un VPC con il CIDR specificato. Amazon VPC crea anche un set di opzioni DHCP predefinito, una tabella di routing principale e una lista di controllo degli accessi alla rete (ACL) predefinita.
New-EC2VPC -CidrBlock 10.0.0.0/16Output:
CidrBlock : 10.0.0.0/16 DhcpOptionsId : dopt-1a2b3c4d InstanceTenancy : default IsDefault : False State : pending Tags : {} VpcId : vpc-12345678-
Per i dettagli sull'API, vedi CreateVpc nel AWS Strumenti per PowerShell Riferimento al cmdlet (V4).
-
- Utensili per PowerShell V5
-
Esempio 1: questo esempio crea un VPC con il CIDR specificato. Amazon VPC crea anche un set di opzioni DHCP predefinito, una tabella di routing principale e una lista di controllo degli accessi alla rete (ACL) predefinita.
New-EC2VPC -CidrBlock 10.0.0.0/16Output:
CidrBlock : 10.0.0.0/16 DhcpOptionsId : dopt-1a2b3c4d InstanceTenancy : default IsDefault : False State : pending Tags : {} VpcId : vpc-12345678-
Per i dettagli sull'API, vedi CreateVpc nel AWS Strumenti per PowerShell Riferimento al cmdlet (V5).
-
- Python
-
- SDK for Python (Boto3)
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. class VpcWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions.""" def __init__(self, ec2_client: boto3.client): """ Initializes the VpcWrapper 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 @classmethod def from_client(cls) -> "VpcWrapper": """ Creates a VpcWrapper instance with a default EC2 client. :return: An instance of VpcWrapper initialized with the default EC2 client. """ ec2_client = boto3.client("ec2") return cls(ec2_client) def create(self, cidr_block: str) -> str: """ Creates a new Amazon VPC with the specified CIDR block. :param cidr_block: The CIDR block for the new VPC, such as '10.0.0.0/16'. :return: The ID of the new VPC. """ try: response = self.ec2_client.create_vpc(CidrBlock=cidr_block) vpc_id = response["Vpc"]["VpcId"] waiter = self.ec2_client.get_waiter("vpc_available") waiter.wait(VpcIds=[vpc_id]) return vpc_id except ClientError as client_error: logging.error( "Couldn't create the vpc. Here's why: %s", client_error.response["Error"]["Message"], ) raise-
Per i dettagli sull'API, vedi CreateVpc nel AWS Riferimento alle API SDK per Python (Boto3).
-
- Ruby
-
- SDK per Ruby
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. require 'aws-sdk-ec2' # Creates a virtual private cloud (VPC) in # Amazon Virtual Private Cloud (Amazon VPC) and then tags # the VPC. # # @param ec2_resource [Aws::EC2::Resource] An initialized # Amazon Elastic Compute Cloud (Amazon EC2) resource object. # @param cidr_block [String] The IPv4 CIDR block for the subnet. # @param tag_key [String] The key portion of the tag for the VPC. # @param tag_value [String] The value portion of the tag for the VPC. # @return [Boolean] true if the VPC was created and tagged; # otherwise, false. # @example # exit 1 unless vpc_created_and_tagged?( # Aws::EC2::Resource.new(region: 'us-west-2'), # '10.0.0.0/24', # 'my-key', # 'my-value' # ) def vpc_created_and_tagged?( ec2_resource, cidr_block, tag_key, tag_value ) vpc = ec2_resource.create_vpc(cidr_block: cidr_block) # Create a public DNS by enabling DNS support and DNS hostnames. vpc.modify_attribute(enable_dns_support: { value: true }) vpc.modify_attribute(enable_dns_hostnames: { value: true }) vpc.create_tags(tags: [{ key: tag_key, value: tag_value }]) puts "Created VPC with ID '#{vpc.id}' and tagged with key " \ "'#{tag_key}' and value '#{tag_value}'." true rescue StandardError => e puts e.message false end # Example usage: def run_me cidr_block = '' tag_key = '' tag_value = '' region = '' # Print usage information and then stop. if ARGV[0] == '--help' || ARGV[0] == '-h' puts 'Usage: ruby ec2-ruby-example-create-vpc.rb ' \ 'CIDR_BLOCK TAG_KEY TAG_VALUE REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. puts 'Example: ruby ec2-ruby-example-create-vpc.rb ' \ '10.0.0.0/24 my-key my-value us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? cidr_block = '10.0.0.0/24' tag_key = 'my-key' tag_value = 'my-value' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else cidr_block = ARGV[0] tag_key = ARGV[1] tag_value = ARGV[2] region = ARGV[3] end ec2_resource = Aws::EC2::Resource.new(region: region) if vpc_created_and_tagged?( ec2_resource, cidr_block, tag_key, tag_value ) puts 'VPC created and tagged.' else puts 'VPC not created or not tagged.' end end run_me if $PROGRAM_NAME == __FILE__-
Per i dettagli sull'API, vedi CreateVpc nel AWS SDK per Ruby Riferimento API.
-
- SAP ABAP
-
- SDK per SAP ABAP
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. " iv_cidr_block = '10.0.0.0/16' TRY. oo_result = lo_ec2->createvpc( iv_cidrblock = iv_cidr_block ). " oo_result is returned for testing purposes. " DATA(lv_vpc_id) = oo_result->get_vpc( )->get_vpcid( ). MESSAGE 'Created VPC.' 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.-
Per i dettagli sull'API, vedi CreateVpc nel AWS Riferimento all'API SDK per SAP ABAP.
-
Per un elenco completo di AWS Guide per sviluppatori SDK ed esempi di codice, consulta Crea EC2 risorse Amazon utilizzando un AWS SDK. Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.