如何在CloudFormation模板中为CloudFront分发配置核心防护与速率限制
如何在CloudFormation模板中为CloudFront分发配置核心防护与速率限制
看起来你是想在CloudFormation里配置CloudFront控制台「安全」标签里的那些基础防护功能对吧?我来帮你梳理一下怎么在现有模板里补上这些配置——主要涉及AWS Shield防护、WAF关联、速率限制这几个核心部分,下面直接结合你的现有模板来修改说明:
1. 关联WAF WebACL(核心防护的基础)
CloudFront的基础安全防护大多依赖WAF来实现,比如SQL注入防护、XSS防护、速率限制这些。你需要先创建一个WAFv2 WebACL(如果还没有的话),然后在CloudFront分发的DistributionConfig里添加WebACLId字段,指向这个WebACL的ARN。
2. 启用AWS Shield防护
- Shield Standard是CloudFront默认启用的,不需要额外配置;
- 如果要启用Shield Advanced(更高级的DDoS防护),需要单独创建
AWS::Shield::Protection资源,关联你的CloudFront分发。
3. 配置速率限制
速率限制可以通过两种方式实现:
- WAF速率规则:在你的WAF WebACL里添加速率限制规则,控制单IP的请求频率;
- CloudFront内置速率限制:创建
AWS::CloudFront::RateLimitingPolicy,然后在对应的CacheBehavior里关联这个策略。
修改后的完整CloudFormation模板示例
下面是在你的原有配置基础上,添加了安全防护相关配置的版本:
# 假设你已经定义了FrontendS3Bucket、FrontendS3OAI、HttpApi这些参数/资源 # 可选:如果要启用Shield Advanced,添加这个资源 CloudFrontShieldProtection: Type: AWS::Shield::Protection Properties: Name: CloudFront-Distribution-Shield-Protection ResourceArn: !GetAtt CloudFrontDistribution.Arn CloudFrontDistribution: Type: AWS::CloudFront::Distribution Properties: DistributionConfig: # 添加WAF WebACL关联,替换成你的WebACL ARN WebACLId: !Sub 'arn:aws:wafv2:${AWS::Region}:${AWS::AccountId}:global/webacl/YourWebACLName/YourWebACLId' Origins: - Id: S3Origin DomainName: Fn::Join: - '' - - !Ref FrontendS3Bucket - '.s3-${env:REGION}.amazonaws.com' S3OriginConfig: OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${FrontendS3OAI}' - Id: ApiGatewayOrigin DomainName: Fn::Join: - '' - - !Ref HttpApi - '.execute-api.${env:REGION}.amazonaws.com' CustomOriginConfig: OriginProtocolPolicy: https-only OriginSSLProtocols: - TLSv1.2 DefaultRootObject: index.html DefaultCacheBehavior: TargetOriginId: S3Origin CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # Managed-CachingOptimized ViewerProtocolPolicy: https-only # 可选:关联CloudFront速率限制策略(如果用内置速率限制) # RateLimitingPolicyId: !Ref MyCloudFrontRateLimitingPolicy CacheBehaviors: - TargetOriginId: ApiGatewayOrigin PathPattern: /api/* ViewerProtocolPolicy: https-only OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # Managed-AllViewerExceptHostHeader CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # Managed-CachingDisabled AllowedMethods: - GET - HEAD - OPTIONS - PUT - PATCH - POST - DELETE # 可选:给API路径单独配置速率限制 # RateLimitingPolicyId: !Ref ApiRateLimitingPolicy Enabled: true # 可选:创建CloudFront速率限制策略示例 MyCloudFrontRateLimitingPolicy: Type: AWS::CloudFront::RateLimitingPolicy Properties: RateLimitingPolicyConfig: Name: Frontend-Rate-Limit RateLimitThreshold: 100 # 每分钟允许的请求数 RateLimitIntervalInSeconds: 60 # 时间窗口,单位秒
一些额外说明
- 如果你还没有创建WAF WebACL,可以用
AWS::WAFv2::WebACL资源来定义,里面可以添加预托管的防护规则(比如AWSManagedRulesCommonRuleSet)和自定义的速率限制规则; - CloudFront的Bot Management功能也可以在
CacheBehavior里添加BotManagementConfig字段来启用,比如设置Enabled: true来开启基础的Bot检测; - 记得替换模板里的占位符(比如
YourWebACLName、YourWebACLId)为你实际的资源信息。
备注:内容来源于stack exchange,提问作者Eemeli Ingervo
相关产品推荐
相关产品推荐

