|
| 1 | +from aws_cdk import Aws, CfnOutput, RemovalPolicy |
1 | 2 | from aws_cdk import aws_apigateway as apigateway |
| 3 | +from aws_cdk import aws_iam as iam |
| 4 | +from aws_cdk import aws_logs as logs |
2 | 5 | from aws_cdk import aws_wafv2 as waf |
3 | 6 | from constructs import Construct |
4 | 7 |
|
@@ -86,3 +89,40 @@ def __init__(self, scope: Construct, id: str, api: apigateway.RestApi, **kwargs) |
86 | 89 |
|
87 | 90 | # Associate WAF with API Gateway |
88 | 91 | waf.CfnWebACLAssociation(self, 'ApiGatewayWafAssociation', resource_arn=api.deployment_stage.stage_arn, web_acl_arn=web_acl.attr_arn) |
| 92 | + |
| 93 | + # Enable logging for WAF, must start with 'aws-waf-logs-' prefix |
| 94 | + log_group_name = f'aws-waf-logs-{id}' |
| 95 | + # Create CloudWatch Log Group for WAF logging |
| 96 | + waf_log_group = logs.LogGroup( |
| 97 | + self, |
| 98 | + 'WafLogGroup', |
| 99 | + log_group_name=log_group_name, |
| 100 | + retention=logs.RetentionDays.TWO_WEEKS, |
| 101 | + removal_policy=RemovalPolicy.DESTROY, |
| 102 | + ) |
| 103 | + |
| 104 | + # Attach resource policy to allow WAF to write to the log group |
| 105 | + waf_log_group.add_to_resource_policy( |
| 106 | + iam.PolicyStatement( |
| 107 | + effect=iam.Effect.ALLOW, |
| 108 | + principals=[iam.AnyPrincipal()], |
| 109 | + actions=['logs:PutLogEvents', 'logs:CreateLogStream', 'logs:DescribeLogGroups'], |
| 110 | + resources=[f'{waf_log_group.log_group_arn}:*'], |
| 111 | + ) |
| 112 | + ) |
| 113 | + |
| 114 | + # Output the Log Group ARN for visibility |
| 115 | + CfnOutput(self, id='WafLogGroupArn', value=waf_log_group.log_group_arn).override_logical_id('WafLogGroupArn') |
| 116 | + |
| 117 | + # Construct the Log Group ARN manually as its not available in the CDK |
| 118 | + log_group_arn = f'arn:{Aws.PARTITION}:logs:{Aws.REGION}:{Aws.ACCOUNT_ID}:log-group:{log_group_name}:*' |
| 119 | + |
| 120 | + enable_waf_logging = waf.CfnLoggingConfiguration( |
| 121 | + self, |
| 122 | + 'WafLoggingConfiguration', |
| 123 | + resource_arn=web_acl.attr_arn, |
| 124 | + log_destination_configs=[log_group_arn], |
| 125 | + ) |
| 126 | + |
| 127 | + web_acl.node.add_dependency(waf_log_group) |
| 128 | + enable_waf_logging.node.add_dependency(web_acl) # Ensure WebACL is created first |
0 commit comments