Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(cloudfront): add
attachWebAclId
method for Distribution (#30567)
### Reason for this change I often create a custom construct for a WAF only. I also create resources (such as API Gateway, ALB, etc...) that attach the WAF in separate constructs. Instead of attaching the WAF in the target resource's construct, I create a method for attaching it in the WAF's construct. In this way, the constructs can be loosely coupled, and the target resource's constructs can be more simply. The WAF can also be attached to multiple resources at once later. ```ts export class Waf extends Construct { public readonly webAcl: CfnWebACL; constructor(scope: Construct, id: string, props: WafProps) { super(scope, id); this.webAcl = new CfnWebACL(this, 'WebAcl', { // ... }, }); public attachToRegionalResource(id: string, resourceArn: string) { new CfnWebACLAssociation(this, `${id}Association`, { resourceArn: resourceArn, webAclArn: this.webAcl.attrArn, }); } } const waf = new Waf(this, 'Waf', { /* props */ }); waf.attachToRegionalResource('A', resourceA); waf.attachToRegionalResource('B', resourceB); waf.attachToRegionalResource('C', resourceC); ``` However, when attaching a WAF to a CloudFront, the WAF attaching configuration needs to be defined through CloudFront props, rather than using CfnWebACLAssociation. To do this with the above WAF construct, a method is needed to pass a pre-defined CloudFront and override the properties of that definition with an escape hatch. This is a bit complicated. ```ts public attachToCloudFront(distribution: Distribution) { // override the webAcl using escape hatch } ``` In other words, it would be good if CloudFront also had a mechanism (like CfnWebACLAssociation) to attach WAF after defining resources. This would allow WAF custom constructs to be more generic. ### Description of changes Add `attachWebAclId` method for Distribution. ```ts declare const bucketOrigin: origins.S3Origin; declare const webAcl: wafv2.CfnWebACL; const distribution = new cloudfront.Distribution(stack, 'Distribution', { defaultBehavior: { origin: bucketOrigin }, }); distribution.attachWebAclId(webAcl.attrArn); ``` ### Description of how you validated changes Both of unit and integ tests. ### Checklist - [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md) ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
- Loading branch information