44 aws_autoscaling as autoscaling ,
55 aws_ec2 as ec2 ,
66 aws_elasticloadbalancingv2 as elbv2 ,
7+ aws_certificatemanager as acm ,
78 App , CfnOutput , Stack
89)
910
@@ -12,13 +13,15 @@ class LoadBalancerStack(Stack):
1213 def __init__ (self , app : App , id : str ) -> None :
1314 super ().__init__ (app , id )
1415
16+ # Create a VPC for our infrastructure
1517 vpc = ec2 .Vpc (self , "VPC" )
1618
19+ # Read and prepare user data script for EC2 instances
1720 data = open ("./httpd.sh" , "rb" ).read ()
1821 httpd = ec2 .UserData .for_linux ()
1922 httpd .add_commands (str (data ,'utf-8' ))
2023
21-
24+ # Create an Auto Scaling Group with EC2 instances
2225 asg = autoscaling .AutoScalingGroup (
2326 self ,
2427 "ASG" ,
@@ -30,19 +33,46 @@ def __init__(self, app: App, id: str) -> None:
3033 user_data = httpd ,
3134 )
3235
36+ # Create an Application Load Balancer
3337 lb = elbv2 .ApplicationLoadBalancer (
3438 self , "LB" ,
3539 vpc = vpc ,
3640 internet_facing = True )
3741
38- listener = lb .add_listener ("Listener" , port = 80 )
39- listener .add_targets ("Target" , port = 80 , targets = [asg ])
40- listener .connections .allow_default_port_from_any_ipv4 ("Open to the world" )
42+ # Create HTTP listener with redirect
43+ http_listener = lb .add_listener (
44+ "HttpListener" ,
45+ port = 80 ,
46+ default_action = elbv2 .ListenerAction .redirect (
47+ port = "443" ,
48+ protocol = "HTTPS" ,
49+ permanent = True ,
50+ host = "#{host}" ,
51+ path = "/#{path}" ,
52+ query = "#{query}"
53+ )
54+ )
55+
56+ # Create HTTPS listener
57+ https_listener = lb .add_listener (
58+ "HttpsListener" ,
59+ port = 443 ,
60+ certificates = [elbv2 .ListenerCertificate .from_arn ("certificate_arn" )],
61+ ssl_policy = elbv2 .SslPolicy .RECOMMENDED
62+ )
63+
64+ # Add target group to HTTPS listener
65+ https_listener .add_targets ("Target" , port = 80 , targets = [asg ])
66+ https_listener .connections .allow_default_port_from_any_ipv4 ("Open to the world" )
4167
68+ # Configure Auto Scaling based on request count
4269 asg .scale_on_request_count ("AModestLoad" , target_requests_per_minute = 60 )
70+
71+ # Output the Load Balancer DNS name
4372 CfnOutput (self ,"LoadBalancer" ,export_name = "LoadBalancer" ,value = lb .load_balancer_dns_name )
4473
4574
75+ # Initialize the CDK app and create the stack
4676app = App ()
4777LoadBalancerStack (app , "LoadBalancerStack" )
4878app .synth ()
0 commit comments