# Create or delete a subnet

Reserve part of a network's range for one zone, so the instances you launch into it get addresses there and run in that zone.

Replace the network id with your own.

## Prerequisites

- Permission for `ec2:CreateSubnet`; deleting needs `ec2:DeleteSubnet`.
- Room in the subnets-per-VPC quota.

## Create a subnet

**Console:** not available. Subnets are created with the API, the CLI or Terraform; the network's **Subnets** tab lists them.

**CLI**
```sh
dcloud ec2 subnets create vpc-uuid --cidr-block 10.0.2.0/24 \
  --availability-zone-id de1b --name app-b
```

**API**
```http
POST /ec2/api/vpcs/0ea56c91-0000-4000-8000-000000000001/subnets
{ "cidrBlock": "10.0.2.0/24", "availabilityZoneId": "de1b", "name": "app-b" }
```

**Terraform**
```hcl
resource "dcloud_subnet" "app_b" {
  vpc_id               = dcloud_vpc.prod.id
  cidr_block           = "10.0.2.0/24"
  availability_zone_id = "de1b"
}
```

Without a zone, the subnet is in the region's default zone (`de1a` in `de1`). Nothing is created
at the provider: the subnet is a part of the network's range kept for one zone. The answer is `201`
with the subnet and its `availableIpCount`. The request is refused with:

- `400` "A subnet is between /16 and /28", "… does not start on a /24 boundary", "… is outside
  the VPC's range …" or "… overlaps the subnet …".
- `400` "… is not an availability zone of de1", or `409` "Availability zone … is …; choose another
  zone" when the zone is not available.
- `404` "VPC not found".

Launch into it with `subnetId` (see [Launch an instance](launch-an-instance.md)): the instance gets
an address in the range and runs in the subnet's zone. A launch whose subnet has no free address is
refused with `409` ("Subnet … has no free addresses left" or "No free address in …").

## Delete a subnet

**Console:** not available. Subnets are deleted with the API, the CLI or Terraform.

**CLI**
```sh
dcloud ec2 subnets delete subnet-uuid
```

**API**
```http
DELETE /ec2/api/subnets/5b1c0d2e-0000-4000-8000-000000000003
```

**Terraform**
Remove the `dcloud_subnet` resource and run `terraform apply`.

The delete is refused with `409` while an instance that is not terminated holds an address in it
("… instance(s) still hold an address in …; terminate them first"), or while a database still uses
the range ("… is still in use by database …; delete that first").

## Related

- [Networks and addresses](networks-and-addresses.md)
- `ec2.subnets.create` · `dcloud ec2 subnets list` · `dcloud_subnet`
