

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# À utiliser `CreateSubnet`avec unAWSSDK ou CLI
<a name="example_ec2_CreateSubnet_section"></a>

Les exemples de code suivants illustrent comment utiliser `CreateSubnet`.

Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans les exemples de code suivants : 
+  [Création d'un réseau privé virtuel de base](example_vpc_GettingStartedCLI_section.md) 
+  [Commencer à utiliser les bases de données graphiques](example_ec2_GettingStarted_064_section.md) 
+  [Commencer à utiliser les passerelles de transit réseau](example_vpc_TransitGatewayGettingStarted_section.md) 
+  [Réseau privé virtuel avec serveurs privés](example_vpc_GettingStartedPrivate_section.md) 
+  [Utilisation de connexions d'appairage réseau](example_ec2_GettingStarted_015_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**Exemple 1 : création d’un sous-réseau avec un bloc CIDR IPv4 uniquement**  
L’exemple `create-subnet` suivant crée un sous-réseau dans le VPC spécifié avec le bloc CIDR IPv4 spécifié.  

```
aws ec2 create-subnet \
    --vpc-id {{vpc-081ec835f3EXAMPLE}} \
    --cidr-block {{10.0.0.0/24}} \
    --tag-specifications {{ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv4-only-subnet}]}}
```
Sortie :  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0e99b93155EXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv4-only-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0e99b93155EXAMPLE"
    }
}
```
**Exemple 2 : création d’un sous-réseau avec des blocs CIDR IPv4 et IPv6**  
L’exemple `create-subnet` suivant crée un sous-réseau dans le VPC spécifié avec les blocs CIDR IPv4 et IPv6 spécifiés.  

```
aws ec2 create-subnet \
    --vpc-id {{vpc-081ec835f3EXAMPLE}} \
    --cidr-block {{10.0.0.0/24}} \
    --ipv6-cidr-block {{2600:1f16:cfe:3660::/64}} \
    --tag-specifications {{ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv4-ipv6-subnet}]}}
```
Sortie :  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0736441d38EXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "subnet-cidr-assoc-06c5f904499fcc623",
                "Ipv6CidrBlock": "2600:1f13:cfe:3660::/64",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                }
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv4-ipv6-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0736441d38EXAMPLE"
    }
}
```
**Exemple 3 : création d’un sous-réseau avec un bloc CIDR IPv6 uniquement**  
L’exemple `create-subnet` suivant crée un sous-réseau dans le VPC spécifié avec le bloc CIDR IPv6 spécifié.  

```
aws ec2 create-subnet \
    --vpc-id {{vpc-081ec835f3EXAMPLE}} \
    --ipv6-native \
    --ipv6-cidr-block {{2600:1f16:115:200::/64}} \
    --tag-specifications {{ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv6-only-subnet}]}}
```
Sortie :  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 0,
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-03f720e7deEXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": true,
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "subnet-cidr-assoc-01ef639edde556709",
                "Ipv6CidrBlock": "2600:1f13:cfe:3660::/64",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                }
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv6-only-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-03f720e7deEXAMPLE"
    }
}
```
Pour plus d’informations, consultez [VPC et sous-réseaux](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) dans le *Guide de l’utilisateur Amazon VPC*.  
+  Pour plus de détails sur l'API, reportez-vous [CreateSubnet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-subnet.html)à la section *Référence des AWS CLI commandes*. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**Exemple 1 : cet exemple crée un sous-réseau pour le CIDR spécifié.**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**Sortie** :  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  Pour plus de détails sur l'API, reportez-vous [CreateSubnet](https://docs.aws.amazon.com/powershell/v4/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V4)*. 

**Outils pour PowerShell V5**  
**Exemple 1 : cet exemple crée un sous-réseau pour le CIDR spécifié.**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**Sortie** :  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  Pour plus de détails sur l'API, reportez-vous [CreateSubnet](https://docs.aws.amazon.com/powershell/v5/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V5)*. 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples). 

```
require 'aws-sdk-ec2'

# Creates a subnet within a virtual private cloud (VPC) in
# Amazon Virtual Private Cloud (Amazon VPC) and then tags
# the subnet.
#
# Prerequisites:
#
# - A VPC in Amazon VPC.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param vpc_id [String] The ID of the VPC for the subnet.
# @param cidr_block [String] The IPv4 CIDR block for the subnet.
# @param availability_zone [String] The ID of the Availability Zone
#   for the subnet.
# @param tag_key [String] The key portion of the tag for the subnet.
# @param tag_vlue [String] The value portion of the tag for the subnet.
# @return [Boolean] true if the subnet was created and tagged;
#   otherwise, false.
# @example
#   exit 1 unless subnet_created_and_tagged?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     'vpc-6713dfEX',
#     '10.0.0.0/24',
#     'us-west-2a',
#     'my-key',
#     'my-value'
#   )
def subnet_created_and_tagged?(
  ec2_resource,
  vpc_id,
  cidr_block,
  availability_zone,
  tag_key,
  tag_value
)
  subnet = ec2_resource.create_subnet(
    vpc_id: vpc_id,
    cidr_block: cidr_block,
    availability_zone: availability_zone
  )
  subnet.create_tags(
    tags: [
      {
        key: tag_key,
        value: tag_value
      }
    ]
  )
  puts "Subnet created with ID '#{subnet.id}' in VPC with ID '#{vpc_id}' " \
    "and CIDR block '#{cidr_block}' in availability zone " \
    "'#{availability_zone}' and tagged with key '#{tag_key}' and " \
    "value '#{tag_value}'."
  true
rescue StandardError => e
  puts "Error creating or tagging subnet: #{e.message}"
  false
end

# Example usage:
def run_me
  vpc_id = ''
  cidr_block = ''
  availability_zone = ''
  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-subnet.rb ' \
      'VPC_ID CIDR_BLOCK AVAILABILITY_ZONE 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-subnet.rb ' \
      'vpc-6713dfEX 10.0.0.0/24 us-west-2a 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?
    vpc_id = 'vpc-6713dfEX'
    cidr_block = '10.0.0.0/24'
    availability_zone = 'us-west-2a'
    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
    vpc_id = ARGV[0]
    cidr_block = ARGV[1]
    availability_zone = ARGV[2]
    tag_key = ARGV[3]
    tag_value = ARGV[4]
    region = ARGV[5]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if subnet_created_and_tagged?(
    ec2_resource,
    vpc_id,
    cidr_block,
    availability_zone,
    tag_key,
    tag_value
  )
    puts 'Subnet created and tagged.'
  else
    puts 'Subnet not created or not tagged.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  Pour plus de détails sur l'API, reportez-vous [CreateSubnet](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateSubnet)à la section *Référence des AWS SDK pour Ruby API*. 

------

Pour obtenir la liste complète des guides de développement du AWS SDK et des exemples de code, consultez[Création de EC2 ressources Amazon à l'aide d'un AWS SDK](sdk-general-information-section.md). Cette rubrique comprend également des informations sur le démarrage et sur les versions précédentes du kit SDK.