You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 your VPCAddresses that match the prefix length of your SubnetAddresses. The 256 value 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-provided SubnetAddresses is present in the list of valid subnets generated by Fn::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 256 value to something larger (e.g., 65536) to ensure all possible subnets are generated for the check.

内容的提问来源于stack exchange,提问作者Saar peer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:28:19