This is an experimental example. It may not build out of the box
This example is built on Construct Libraries marked "Experimental" and may not be updated for latest breaking changes.
If build is unsuccessful, please create an issue so that we may debug the problem
- Creates a WAF for use with CloudFront and a WAF for use with Load Balancers.
- Both WAF stacks are virtually identical:
waf_cloudfront.pywaf_regional.py
- Each stack is customized for the target usage scenario.
- cdk is a NodeJS app.
- Install NodeJS.
- Use
npmto installcdk
npm install -g cdkpython3 -m venv .venv
source .venv/bin/activate- Each service such as wafv2 (
aws_cdk.aws_wafv2) or ec2 (aws_cdk.aws_ec2), has its own module which must be defined inrequirements.txt.
pip3 install -r requirements.txtTo build this example, you need to be in this example's root directory. Then run the following:
cdk synth- This will build the CloudFormation template. The resulting CloudFormation template will be in the
cdk.outdirectory. - If you want to see the
yamlformatted CDK for a Stack, pass it as a name to thecdk synthcommand:
cdk synth WafCloudFrontStack
cdk synth WafRegionalStackRun cdk deploy. This will deploy / redeploy your Stack to your AWS Account.
After the deployment, you will be able to assign the WAF to the CloudFront or Load Balancer resources.
- The WAF leverages the AWS Managed rules for most of the enabled rule list.
- The list of available ruls can be quickly found using the AWS CLI:
aws wafv2 list-available-managed-rule-groups --scope CLOUDFRONT
aws wafv2 list-available-managed-rule-groups --scope REGIONAL- The example code includes a rule based on the geographic region of the source IP.
- If the IP is outside the list of country codes, then the IP will be blocked.
- The example code includes a rule that will restrict connections based on flow rate.
- In the included example, if the connection count is higher than 100 in a 5 minute period, the connection will be blocked.
- Each WAF stack produces a CloudFormation Export.
- The CloudFormation Export records the WAF ARN for use with other stacks:
- The exports are named:
WafCloudFrontStack:WafAclCloudFrontArnWafRegionalStack:WafAclRegionalArn
from aws_cdk import (
core,
aws_wafv2 as wafv2,
aws_cloudfront as cloudfront,
)
wafacl_cloudfront_arn = core.Fn.import_value("WafCloudFrontStack:WafAclCloudFrontArn");
cloudfront.CloudFrontWebDistribution(self, 'frontendDistribution', {
..
..
..
web_acl_id: wafacl_cloudfront_arn
});from aws_cdk import (
core,
aws_wafv2 as wafv2,
aws_appsync as appsync,
)
wafacl_appsync_arn = core.Fn.import_value("WafRegionalStack:WafAclAppSyncArn");
gql = appsync.GraphqlApi(self, 'NeptuneGraphQLApi',
...
...
...
);
wafv2.CfnWebACLAssociation(self, 'NeptuneGraphQLApiWaf',
resourceArn: gql.arn,
webAclArn: wafacl_appsync_arn
)