| 10 | |
| 11 | |
| 12 | class LoadBalancerStack(Stack): |
| 13 | def __init__(self, app: App, id: str) -> None: |
| 14 | super().__init__(app, id) |
| 15 | |
| 16 | # Create a VPC for our infrastructure |
| 17 | vpc = ec2.Vpc(self, "VPC") |
| 18 | |
| 19 | # Read and prepare user data script for EC2 instances |
| 20 | data = open("./httpd.sh", "rb").read() |
| 21 | httpd=ec2.UserData.for_linux() |
| 22 | httpd.add_commands(str(data,'utf-8')) |
| 23 | |
| 24 | # Create an Auto Scaling Group with EC2 instances |
| 25 | asg = autoscaling.AutoScalingGroup( |
| 26 | self, |
| 27 | "ASG", |
| 28 | vpc=vpc, |
| 29 | instance_type=ec2.InstanceType.of( |
| 30 | ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO |
| 31 | ), |
| 32 | machine_image=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), |
| 33 | user_data=httpd, |
| 34 | ) |
| 35 | |
| 36 | # Create an Application Load Balancer |
| 37 | lb = elbv2.ApplicationLoadBalancer( |
| 38 | self, "LB", |
| 39 | vpc=vpc, |
| 40 | internet_facing=True) |
| 41 | |
| 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") |
| 67 | |
| 68 | # Configure Auto Scaling based on request count |
| 69 | asg.scale_on_request_count("AModestLoad", target_requests_per_minute=60) |