--- AWSTemplateFormatVersion: '2010-09-09' Description: Simple VPC with optional secondary CIDR Metadata: AWS::CloudFormation::Interface: ParameterGroups: - Label: default: VPC CIDR ranges Parameters: - VpcCidr - VpcCidrSecondary - Label: default: Subnet Parameters: - SubnetCidr Parameters: VpcCidr: Type: String Description: VPC Primary CIDR Default: "10.0.0.0/24" AllowedPattern: '((\d{1,3})\.){3}\d{1,3}/\d{1,2}' VpcCidrSecondary: Type: String Description: VPC Secondary CIDR (optional) Default: "10.1.0.0/24" AllowedPattern: '(((\d{1,3})\.){3}\d{1,3}/\d{1,2}){0,1}' SubnetCidr: Type: String Description: VPC subnet CIDR Default: "10.0.0.0/24" AllowedPattern: '(((\d{1,3})\.){3}\d{1,3}/\d{1,2}){0,1}' Conditions: VpcCidrSecondaryExists: !Not [!Equals [!Ref VpcCidrSecondary, "" ]] Resources: VPC: Type: AWS::EC2::VPC Properties: CidrBlock: !Ref VpcCidr EnableDnsSupport: true EnableDnsHostnames: true InstanceTenancy: default Tags: - Key: Name Value: !Sub '${AWS::StackName}' VPCSecondaryCIDR: Type: AWS::EC2::VPCCidrBlock Condition: VpcCidrSecondaryExists Properties: CidrBlock: !Ref VpcCidrSecondary VpcId: !Ref VPC # Use "DependsOn: VPCReady" to wait until VPC AND all secondary CIDRs are ready. # Unfortunately this only creates 1-way dependency making sure CIRDs are in place # before creating subnets. When removing CIRD and subnet, you must do it in # 2 steps. First update to remove subnet, and then the second update to remove CIDR. # CIRD doesnt have connection to subnet, removal can start while subnet still exists # and will result an error (but that will not stop the update). VPCReady: Type: AWS::CloudFormation::WaitConditionHandle Metadata: SecondaryCIDRready: !If [ VpcCidrSecondaryExists, !Ref VPCSecondaryCIDR, "" ] Subnet: Type: AWS::EC2::Subnet DependsOn: VPCReady Properties: VpcId: !Ref VPC AvailabilityZone: !Sub ${AWS::Region}a CidrBlock: !Ref SubnetCidr