Search code examples
c#amazon-web-servicesaws-cdkvpc

AWS CDK: Vpc subnet conflicts with another subnet


I want to create an OpenSearch domain in AWS CDK within a VPC. I've made some progress, but I'm stuck with an issue regarding CIDR.

var vpc = new Vpc(scope, "Vpc");
var subnet = new Subnet(scope, "Subnet", new SubnetProps
{
     VpcId = vpc.VpcId,
     CidrBlock = "10.0.1.0/24",
     AvailabilityZone = "us-east-1a"
});
var domain = new Domain(scope, "Domain", new DomainProps
{
     Vpc = vpc,
     VpcSubnets = new SubnetSelection[] 
     { 
         new SubnetSelection
         {
             Subnets = new Subnet[]
             {
                 subnet
             }
         }
     },
     SecurityGroups = new SecurityGroup[]
     {
         new SecurityGroup(scope, "SecurityGroup", new SecurityGroupProps
         {
             Vpc = vpc
         })
     },
     // other property initializations are omitted
}

The error I'm getting is The CIDR '10.0.1.0/24' conflicts with another subnet. How can this be true if I'm creating a brand new Vpc with only one subnet? I assume there may be more subnets that are created implicitly. How can I address this issue?

Currently I don't care for multiple AZs so I need to place the domain within a single subnet.


Solution

  • The VPC construct's IpAddresses and SubnetConfiguration props allow you to customise the CIDR range and subnets.

    Your VPC constructor is not defining these props, so the defaults (10.0.0.0/16 allocated to 2 subnets) are applied instead. These defaults are conflicting with your manually created subnet.

    Pardon my bad C#, but you'll want a VPC constructor something like this:

    Vpc vpc = new Vpc(this, "VPC", new VpcProps {
        IpAddresses = IpAddresses.Cidr("10.0.0.0/24")
        MaxAzs = 1,
        SubnetConfiguration = new ISubnetConfiguration[]
        {
            new SubnetConfiguration
            {
                SubnetType = SubnetType.PUBLIC,
                Name = "Public"
            }
        }
    });
    

    See the Ip Address Management section in the docs for details.