|
| 1 | +from aws_cdk import ( |
| 2 | + NestedStack, |
| 3 | + aws_ec2 as ec2, |
| 4 | + aws_servicediscovery as servicediscovery, |
| 5 | + aws_ecs as ecs, |
| 6 | + Duration, |
| 7 | + aws_logs as logs, |
| 8 | + aws_iam as iam, |
| 9 | + aws_iam as iam, |
| 10 | + aws_ecr_assets as ecr_assets, |
| 11 | + aws_elasticloadbalancingv2 as elbv2, |
| 12 | + RemovalPolicy, |
| 13 | + CfnOutput |
| 14 | + |
| 15 | +) |
| 16 | +from constructs import Construct |
| 17 | + |
| 18 | +class EcsStack(NestedStack): |
| 19 | + |
| 20 | + def __init__(self, scope: Construct, construct_id: str, vpc: ec2.Vpc, frontend_repository: ecr_assets.DockerImageAsset, backend_data_repository: ecr_assets.DockerImageAsset, **kwargs) -> None: |
| 21 | + super().__init__(scope, construct_id, **kwargs) |
| 22 | + # Creating the ECS Cluster and the cloud map namespace |
| 23 | + ecs_cluster = ecs.Cluster(self, "ECSCluster", |
| 24 | + vpc=vpc, |
| 25 | + cluster_name="App-Service-Connect-Cluster", |
| 26 | + container_insights=True) |
| 27 | + default_cloud_map_namespace=ecs_cluster.add_default_cloud_map_namespace(name="scapp.local", use_for_service_connect=True, type=servicediscovery.NamespaceType.DNS_PRIVATE) |
| 28 | + # Creating the Cloudwatch log group where ECS Logs will be stored |
| 29 | + ECSServiceLogGroup = logs.LogGroup(self, "ECSServiceLogGroup", |
| 30 | + log_group_name=f"{ecs_cluster.cluster_name}-service", |
| 31 | + removal_policy=RemovalPolicy.DESTROY, |
| 32 | + retention=logs.RetentionDays.FIVE_DAYS, |
| 33 | + ) |
| 34 | + # Creating the task and execution IAM roles that the containers will assume to read and write to cloudwatch, Task Execution |
| 35 | + # Role will read from ECR |
| 36 | + ECSTaskIamRole = iam.Role(self, "ECSTaskIamRole", |
| 37 | + assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"), |
| 38 | + managed_policies=[ |
| 39 | + iam.ManagedPolicy.from_aws_managed_policy_name("CloudWatchFullAccess"), |
| 40 | + ], |
| 41 | + ) |
| 42 | + TaskExecutionRole = iam.Role(self, "TaskexecutionRole", |
| 43 | + assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"), |
| 44 | + managed_policies=[ |
| 45 | + iam.ManagedPolicy.from_aws_managed_policy_name("AmazonEC2ContainerRegistryReadOnly"), |
| 46 | + iam.ManagedPolicy.from_aws_managed_policy_name("CloudWatchLogsFullAccess"), |
| 47 | + ], |
| 48 | + ) |
| 49 | + # ECS Security group, this will allow access from the Load Balancer and allow LAN access so that the |
| 50 | + # ECS containers can talk to eachother on port 5001 (which is the port that the backend uses) |
| 51 | + ECSSecurityGroup = ec2.SecurityGroup(self, "ECSSecurityGroup", |
| 52 | + vpc=vpc, |
| 53 | + description="ECS Security Group", |
| 54 | + allow_all_outbound=True, |
| 55 | + ) |
| 56 | + ECSSecurityGroup.add_ingress_rule(ec2.Peer.ipv4(vpc.vpc_cidr_block), ec2.Port.tcp(5001), description="All traffic within VPC",) |
| 57 | + # Task definitions for the frontend and backend |
| 58 | + frontend_definition = ecs.FargateTaskDefinition( |
| 59 | + self, f"FrontendTaskDefinition", |
| 60 | + family="frontend", |
| 61 | + cpu=256, |
| 62 | + memory_limit_mib=512, |
| 63 | + task_role=TaskExecutionRole, |
| 64 | + execution_role=ECSTaskIamRole |
| 65 | + ) |
| 66 | + backend_definition = ecs.FargateTaskDefinition( |
| 67 | + self, f"BackendTaskDefinition", |
| 68 | + family="backend", |
| 69 | + cpu=256, |
| 70 | + memory_limit_mib=512, |
| 71 | + task_role=TaskExecutionRole, |
| 72 | + execution_role=ECSTaskIamRole |
| 73 | + ) |
| 74 | + |
| 75 | + # Containers for each application, when the frontend is hit on /get-data it makes a call to the backend endpoint /data |
| 76 | + frontend_container = frontend_definition.add_container("FrontendContainer", |
| 77 | + container_name="frontend-app", |
| 78 | + image=ecs.ContainerImage.from_docker_image_asset(frontend_repository), |
| 79 | + port_mappings=[ |
| 80 | + ecs.PortMapping( |
| 81 | + container_port=5000, # Flask app is running on 5001 |
| 82 | + host_port=5000, |
| 83 | + name="frontend" # Name of the port mapping |
| 84 | + ) |
| 85 | + ], |
| 86 | + logging=ecs.LogDriver.aws_logs(stream_prefix="ecs-logs")) |
| 87 | + backend_container = backend_definition.add_container("BackendContainer", |
| 88 | + image=ecs.ContainerImage.from_docker_image_asset(backend_data_repository), |
| 89 | + port_mappings=[ |
| 90 | + ecs.PortMapping( |
| 91 | + container_port=5001, # Flask app is running on 5001 |
| 92 | + host_port=5001, |
| 93 | + name="data" # Name of the port mapping |
| 94 | + |
| 95 | + ) |
| 96 | + ], |
| 97 | + container_name="backend", |
| 98 | + logging=ecs.LogDriver.aws_logs(stream_prefix="ecs-logs")) |
| 99 | + # Creating the service definitions and port mappings |
| 100 | + frontend_service = ecs.FargateService(self, "FrontendService", |
| 101 | + cluster=ecs_cluster, |
| 102 | + task_definition=frontend_definition, |
| 103 | + desired_count=1, |
| 104 | + max_healthy_percent=200, |
| 105 | + min_healthy_percent=100, |
| 106 | + vpc_subnets=ec2.SubnetSelection(one_per_az=True, subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS), |
| 107 | + security_groups=[ECSSecurityGroup], |
| 108 | + service_connect_configuration=ecs.ServiceConnectProps( |
| 109 | + namespace=default_cloud_map_namespace.namespace_name, |
| 110 | + services=[ecs.ServiceConnectService( |
| 111 | + port_mapping_name="frontend", # Logical name for the service |
| 112 | + port=5000, # Container port |
| 113 | + )]), |
| 114 | + service_name="frontend-service") |
| 115 | + backend_service = ecs.FargateService(self, "BackendService", |
| 116 | + cluster=ecs_cluster, |
| 117 | + task_definition=backend_definition, |
| 118 | + desired_count=1, |
| 119 | + max_healthy_percent=200, |
| 120 | + min_healthy_percent=100, |
| 121 | + vpc_subnets=ec2.SubnetSelection(one_per_az=True, subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS), |
| 122 | + security_groups=[ECSSecurityGroup], |
| 123 | + service_connect_configuration=ecs.ServiceConnectProps( |
| 124 | + namespace=default_cloud_map_namespace.namespace_name, |
| 125 | + services=[ecs.ServiceConnectService( |
| 126 | + port_mapping_name="data", # Logical name for the service |
| 127 | + port=5001, # Container port |
| 128 | + )]), |
| 129 | + service_name="backend-service") |
| 130 | + # Creating a public load balancer that will listen on port 80 and forward requests to the frontend ecs container, |
| 131 | + # healthchecks are established on port 5000 |
| 132 | + public_lb_sg = ec2.SecurityGroup(self, "PublicLBSG", vpc=vpc, description="Public LB SG", allow_all_outbound=True) |
| 133 | + target_group = elbv2.ApplicationTargetGroup( |
| 134 | + self, "TargetGroup", |
| 135 | + target_group_name="ecs-target-group", |
| 136 | + vpc=vpc, |
| 137 | + port=80, |
| 138 | + targets=[frontend_service], |
| 139 | + target_type=elbv2.TargetType.IP, |
| 140 | + protocol=elbv2.ApplicationProtocol.HTTP, |
| 141 | + health_check=elbv2.HealthCheck( |
| 142 | + path="/", |
| 143 | + port="5000", |
| 144 | + interval=Duration.seconds(6), |
| 145 | + timeout=Duration.seconds(5), |
| 146 | + healthy_threshold_count=2, |
| 147 | + unhealthy_threshold_count=2, |
| 148 | + ), |
| 149 | + ) |
| 150 | + target_group.set_attribute(key="deregistration_delay.timeout_seconds", |
| 151 | + value="120") |
| 152 | + public_lb_sg.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(80), description="Allow HTTP traffic") |
| 153 | + public_lb = elbv2.ApplicationLoadBalancer(self, "FrontendLB", vpc=vpc, internet_facing=True, security_group=public_lb_sg, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)) |
| 154 | + public_lb.set_attribute(key="idle_timeout.timeout_seconds", value="30") |
| 155 | + listener = public_lb.add_listener("Listener", port=80, default_action=elbv2.ListenerAction.forward(target_groups=[target_group])) |
| 156 | + lb_rule = elbv2.ApplicationListenerRule( |
| 157 | + self, "ListenerRule", |
| 158 | + listener=listener, |
| 159 | + priority=1, |
| 160 | + action=elbv2.ListenerAction.forward(target_groups=[target_group]), |
| 161 | + conditions=[elbv2.ListenerCondition.path_patterns(["*"])], |
| 162 | + ) |
| 163 | + CfnOutput(self, "Load Balancer URL", value=f"http://{public_lb.load_balancer_dns_name}") |
0 commit comments