aws-cloudformationaws-cdkamazon-vpcsubnetcidr

Reassign CIDR blocks to subnets during CFN stack update


I have a CFN stack for my VPC where I first create only public and private subnets, which get assigned default CIDR blocks. Now after a while I need to add isolated subnets to the VPC as well. When I try to update the CFN stack, I get an exception - "The CIDR '10.0.0.0/25' conflicts with another subnet

Is it possible to reassign the CIDR blocks to the subnets after adding more subnets in CFN stack update?

Here's sample code:


    if (<some condition>){
        this.createVpcWithIsolatedSubnets();
    } else {
        this.createVpc() 
    }
createVpc() {
    const vpc = new ec2.Vpc(this, `VPC`, {
        maxAzs: MAX_AZ,
        subnetConfiguration: [
           {
               name: 'Public',
               subnetType: ec2.SubnetType.PUBLIC
           },
           {
               name: 'Private',
               subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS
           }
        ]      
   });
}
createVpcWithIsolatedSubnets() {
            
    const vpc = new ec2.Vpc(this, `VPC`, {
        maxAzs: MAX_AZ,
        subnetConfiguration: [
           {
               name: 'Public',
               subnetType: ec2.SubnetType.PUBLIC
           },
           {
               name: 'Private',
               subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS
           },
           {
               name: 'Isolated',
               subnetType: ec2.SubnetType.PRIVATE_ISOLATED
           }
        ]      
   });
}

Solution

  • The error indicates you are trying to add a new subnet with a CIDR that overlaps with one that already exists. In your CloudFormation template, when creating subnets you can specify the CIDR range to use.

    Also, the documentation for the CIRD property of a subnet mentions that

    If you update this property, we create a new subnet, and then delete the existing one.

    So most likely you are trying to take an existing subnet CIDR and reduce it to something smaller while also adding a new subnet that uses part of the same range. This will cause overlap since CloudFormation will try to make the new subnets first and will only delete the old one during the cleanup phase. You would need to delete the existing subnet in a stack update, then create two new ones with smaller CIDR ranges in a subsequent stack update that runs after the first update has finished.

    It isn't possible to "reassign the CIDR blocks to the subnets" since an update really means deleting the existing one and recreating a new one. Also see subnet sizing. If you can post the relevant parts of the original CFN template and the new one it would be easier to compare to see what CIDRs you are using for the subnets.