AWS CloudFront is a content delivery network (CDN) service that can help absorb and mitigate DDoS attacks by distributing traffic across multiple edge locations and caching content closer to users.
Example Code:
AWS WAF Example Rule to Mitigate DDoS Attacks:
AWSTemplateFormatVersion: '2010-09-09'
Resources:
DDosProtectionRule:
Type: 'AWS::WAFv2::Rule'
Properties:
Name: DDosProtectionRule
Scope: REGIONAL
Priority: 1
Action:
Allow: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
Statement:
RateBasedStatement:
Limit: 1000
AggregateKeyType: IP
AWS Lambda Function for Auto-Scaling Based on CloudWatch Metrics:
import boto3
def scale_out(event, context):
cloudwatch = boto3.client('cloudwatch')
scaling_policy_arn = 'arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id'
response = cloudwatch.get_metric_statistics(
Namespace='AWS/ApplicationELB',
MetricName='RequestCountPerTarget',
Dimensions=[
{
'Name': 'LoadBalancer',
'Value': 'load-balancer-name'
},
],
StartTime='2024-05-15T00:00:00Z',
EndTime='2024-05-15T23:59:59Z',
Period=300,
Statistics=['Sum'],
Unit='Count'
)
request_count = response['Datapoints'][0]['Sum']
if request_count > 10000:
autoscaling = boto3.client('autoscaling')
response = autoscaling.execute_policy(AutoScalingGroupName='auto-scaling-group-name', PolicyName='ScaleOutPolicy')
print(response)