AWS CloudFormation模板子网地址验证:能否用Rules校验子网CIDR归属VPC?
Validate Subnet CIDR is Within VPC CIDR in CloudFormation
Absolutely! You can validate whether your SubnetAddresses CIDR range is contained within VPCAddresses before your CloudFormation stack starts deploying, and this is fully supported using CloudFormation's native Rules functionality.
How to Implement the Validation
Here's how to extend your existing template with a rule that enforces this constraint:
AWSTemplateFormatVersion: "2010-09-09" Parameters: VPCAddresses: Type: String MinLength: "9" MaxLength: "18" Default: "10.0.0.0/16" AllowedPattern: "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})" ConstraintDescription: "must be a valid IP CIDR range of the form x.x.x.x/x." SubnetAddresses: Type: String MinLength: "9" MaxLength: "18" Default: "10.0.0.0/24" AllowedPattern: "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})" ConstraintDescription: "must be a valid IP CIDR range of the form x.x.x.x/x." Rules: SubnetMustBeWithinVpc: Assertions: - Assert: !Contains - !Cidr - !Ref VPCAddresses - 256 # Generates all possible subnets of the target prefix length within the VPC CIDR - !Select [1, !Split ["/", !Ref SubnetAddresses]] - !Ref SubnetAddresses AssertDescription: "The subnet CIDR must be a valid subset of the VPC CIDR range. Please check your input values."
How This Works
Fn::Cidr: This function generates a list of all valid CIDR ranges within yourVPCAddressesthat match the prefix length of yourSubnetAddresses. The256value is a safe upper limit—it will only generate as many subnets as actually exist within the VPC CIDR, so you don't have to adjust it for different VPC sizes.Fn::Contains: This checks if the user-providedSubnetAddressesis present in the list of valid subnets generated byFn::Cidr.- Pre-Deployment Check: CloudFormation runs this rule before creating or updating any resources. If the subnet CIDR isn't within the VPC range, it will immediately throw an error with your custom description, stopping the deployment before any resources are provisioned.
Key Notes
- This is native CloudFormation functionality, so you don't need external tools or Lambda functions—it's lightweight and reliable.
- If you expect to use very large VPC ranges (like /8) and small subnet prefixes, you can increase the
256value to something larger (e.g., 65536) to ensure all possible subnets are generated for the check.
内容的提问来源于stack exchange,提问作者Saar peer
相关产品推荐
相关产品推荐

