def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # import default VPC
        vpc = aws_ec2.Vpc.from_lookup(self, 'VPC', is_default=True)

        # ECS cluster
        cluster = aws_ecs.Cluster(self, 'Cluster', vpc=vpc)

        task = aws_ecs.FargateTaskDefinition(
            self,
            'Task',
            cpu=256,
            memory_limit_mib=512,
        )
        task.add_container(
            'flask',
            image=aws_ecs.ContainerImage.from_asset('flask-docker-app'),
            environment={
                'PLATFORM': 'AWS Fargate :-)'
            }).add_port_mappings(aws_ecs.PortMapping(container_port=5000))

        svc = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self, 'svc', cluster=cluster, task_definition=task)

        core.CfnOutput(self,
                       'SericeURL',
                       value="http://{}".format(
                           svc.load_balancer.load_balancer_dns_name))
示例#2
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create a VPC
        vpc = ec2.Vpc(
            self,
            "WebDemoVPC",
            max_azs=2,
        )  # default is all AZs in region,
        # but you can limit to avoid reaching resource quota

        # Create ECS cluster
        cluster = ecs.Cluster(self, "WebDemoCluster", vpc=vpc)

        # Add an AutoScalingGroup with spot instances to the existing cluster
        cluster.add_capacity(
            "AsgSpot",
            max_capacity=2,
            min_capacity=1,
            desired_capacity=2,
            instance_type=ec2.InstanceType("c5.xlarge"),
            spot_price="0.0735",
            # Enable the Automated Spot Draining support for Amazon ECS
            spot_instance_draining=True)

        # Build Dockerfile from local folder and push to ECR
        image = ecs.ContainerImage.from_asset('app')

        # Create Fargate service
        fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "WebDemoService",
            cluster=cluster,  # Required
            cpu=2048,  # Default is 256 (512 is 0.5 vCPU, 2048 is 2 vCPU)
            desired_count=1,  # Default is 1
            task_image_options=ecs_patterns.
            ApplicationLoadBalancedTaskImageOptions(
                image=image,
                container_port=8501,
            ),
            memory_limit_mib=4096,  # Default is 512
            public_load_balancer=True)  # Default is True

        # Add policies to task role
        fargate_service.task_definition.add_to_task_role_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                actions=["rekognition:*"],
                resources=["*"],
            ))

        # Setup task auto-scaling
        scaling = fargate_service.service.auto_scale_task_count(
            max_capacity=10)
        scaling.scale_on_cpu_utilization(
            "CpuScaling",
            target_utilization_percent=50,
            scale_in_cooldown=core.Duration.seconds(60),
            scale_out_cooldown=core.Duration.seconds(60),
        )
示例#3
0
    def setup_service(self):
        """Setup ALB Fargate service

        Notes
        -----
        The container_name in task_image_options shoue be an exsiting image in
        ECR repository. Otherwise, the CFN stack will be stuck waiting for the image.


        Returns
        -------
        aws_ecs_patterns.ApplicationLoadBalancedFargateService

        """

        service = patterns.ApplicationLoadBalancedFargateService(
            self,
            'FargateService',
            cluster=self.cluster,  # Required
            cpu=256,  # 0.25 CPU
            memory_limit_mib=512,  # 0.5G
            desired_count=2,  # Default is 1
            task_image_options=patterns.
            ApplicationLoadBalancedTaskImageOptions(
                container_name=self.config.api.ecr_repo,
                container_port=80,
                image=ecs.ContainerImage.from_ecr_repository(self.ecr_repo)),
            public_load_balancer=True)
        return service
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here

        vpc = ec2.Vpc(self, "MyVpc", max_azs=2)
        cluster = ecs.Cluster(self, "MyCluster", vpc=vpc)

        task_def = ecs.FargateTaskDefinition(self, "TaskDef")

        app_container = task_def.add_container(
            "AppContainer",
            #   image=ecs.ContainerImage.from_asset(
            #       "myapp")
            image=ecs.ContainerImage.from_registry(
                "mystique/predict-attire-for-weather"))

        app_container.add_port_mappings(
            ecs.PortMapping(container_port=80, protocol=ecs.Protocol.TCP))

        myService = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "myService",
            cluster=cluster,
            desired_count=2,
            task_definition=task_def)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Defines vpc to host Fargate SLB

        vpc = ec2.Vpc(
            self,
            'cdkVPC',
            cidr="10.0.0.0/24",
            # two azs required to host alb
            max_azs=2,
            subnet_configuration=[
                # create private subnet to host fargate service
                ec2.SubnetConfiguration(subnet_type=ec2.SubnetType.PRIVATE,
                                        name="cdkPrivate",
                                        cidr_mask=28),
                # create public subnet to host nat-gateway for private subnet so that amazon-ecs-sample image can be pulled from internet"
                ec2.SubnetConfiguration(subnet_type=ec2.SubnetType.PUBLIC,
                                        name="cdkPublic",
                                        cidr_mask=28),
            ])
        # create cluster to host fargate
        cluster = ecs.Cluster(self, "CDKCluster", vpc=vpc)
        # create fargate and service and alb
        ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "MyFargateService",
            assign_public_ip=False,
            cluster=cluster,
            desired_count=1,
            task_image_options=ecs_patterns.
            ApplicationLoadBalancedTaskImageOptions(
                image=ecs.ContainerImage.from_registry(
                    "amazon/amazon-ecs-sample")),
            public_load_balancer=False)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = ec2.Vpc(
            self,
            "ZephStreamlitVPC",
            max_azs=2,  # default is all AZs in region, 
        )

        cluster = ecs.Cluster(self, "ZephStreamlitCluster", vpc=vpc)

        # Build Dockerfile from local folder and push to ECR
        image = ecs.ContainerImage.from_asset('streamlit-docker')

        # Use an ecs_patterns recipe to do all the rest!
        ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "ZephFargateService",
            cluster=cluster,  # Required
            cpu=256,  # Default is 256
            desired_count=1,  # Default is 1
            task_image_options=ecs_patterns.
            ApplicationLoadBalancedTaskImageOptions(
                image=image,
                container_port=8501),  # Docker exposes 8501 for streamlit
            memory_limit_mib=512,  # Default is 512
            public_load_balancer=True,  # Default is False
        )
示例#7
0
 def airflow_web_service(self, environment):
     service_name = get_webserver_service_name(self.deploy_env)
     family = get_webserver_taskdef_family_name(self.deploy_env)
     task_def = ecs.FargateTaskDefinition(self,
                                          family,
                                          cpu=512,
                                          memory_limit_mib=1024,
                                          family=family)
     task_def.add_container(f"WebWorker-{self.deploy_env}",
                            image=self.image,
                            environment=environment,
                            secrets=self.secrets,
                            logging=ecs.LogDrivers.aws_logs(
                                stream_prefix=family,
                                log_retention=RetentionDays.ONE_DAY))
     task_def.default_container.add_port_mappings(
         ecs.PortMapping(container_port=8080,
                         host_port=8080,
                         protocol=Protocol.TCP))
     # we want only 1 instance of the web server so when new versions are deployed max_healthy_percent=100
     # you have to manually stop the current version and then it should start a new version - done by deploy task
     service = ecs_patterns.ApplicationLoadBalancedFargateService(
         self,
         service_name,
         cluster=self.cluster,  # Required
         service_name=service_name,
         platform_version=ecs.FargatePlatformVersion.VERSION1_4,
         cpu=512,  # Default is 256
         desired_count=1,  # Default is 1
         task_definition=task_def,
         memory_limit_mib=2048,  # Default is 512
         public_load_balancer=True,
         max_healthy_percent=100)
     service.target_group.configure_health_check(path="/health")
     return service
    def fargate_service(self, id, cluster, is_alb=False, desired_count=None):
        if self.task_definition is None:
            raise ValueError(
                "Task definition needs to be set")  # TODO: make this better.

        if desired_count is None:
            desired_count = 1

        if is_alb is False:
            self.service = ecs.FargateService(
                self.stack,
                id,
                task_definition=self.task_definition,
                cluster=cluster,
                desired_count=desired_count)

        else:
            alb = ecs_patterns.ApplicationLoadBalancedFargateService(
                self.stack,
                id,
                task_definition=self.task_definition,
                protocol=elb.ApplicationProtocol.HTTP,
                cluster=cluster,
                desired_count=desired_count)
            self.service = alb.service
示例#9
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        vpc = ec2.Vpc(self, "EcsVpc", max_azs=2, nat_gateways=0)
        vpc.add_s3_endpoint('S3Endpoint')
        vpc.add_interface_endpoint(
            'EcrDockerEndpoint',
            service=ec2.InterfaceVpcEndpointAwsService.ECR_DOCKER)
        vpc.add_interface_endpoint(
            'EcrEndpoint', service=ec2.InterfaceVpcEndpointAwsService.ECR)
        vpc.add_interface_endpoint(
            'CloudWatchLogsEndpoint',
            service=ec2.InterfaceVpcEndpointAwsService.CLOUDWATCH_LOGS)
        cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)
        task_definition = ecs.FargateTaskDefinition(self,
                                                    "DemoServiceTask",
                                                    family="DemoServiceTask")

        image = ecs.ContainerImage.from_asset("service")

        container = task_definition.add_container("app", image=image)
        container.add_port_mappings(ecs.PortMapping(container_port=8080))

        ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "DemoService",
            cluster=cluster,
            desired_count=2,
            task_definition=task_definition)
示例#10
0
    def __init__(self, scope: core.Construct, id: str, vpcId: str,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        cluster = aws_ecs.Cluster(self,
                                  'Cluster',
                                  vpc=scope.node.try_find_child(vpcId))
        task = aws_ecs.FargateTaskDefinition(
            self,
            'Task',
            memory_limit_mib=512,
            cpu=256,
        )

        task.add_container('Nginx',
                           image=aws_ecs.ContainerImage.from_registry(
                               'nginx')).add_port_mappings(
                                   aws_ecs.PortMapping(container_port=80))

        svc = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self, 'FargateService', cluster=cluster, task_definition=task)

        core.CfnOutput(self,
                       'ServiceURL',
                       value='http://{}/'.format(
                           svc.load_balancer.load_balancer_full_name))
示例#11
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = ec2.Vpc(self, "CDKFargateVpc", max_azs=2)

        cluster = ecs.Cluster(self, "CDKFargateCluster", vpc=vpc)

        role = iam.Role.from_role_arn(self, "CDKFargateECSTaskRole", ROLE_ARN)
        image = ecs.ContainerImage.from_registry(ECR_REGISOTRY)
        task_definition = ecs.FargateTaskDefinition(scope=self,
                                                    id="CDKFargateECSTask",
                                                    execution_role=role,
                                                    task_role=role)

        port_mapping = ecs.PortMapping(container_port=8080, host_port=8080)
        task_definition.add_container(
            id="CDKFargateContainer",
            image=image).add_port_mappings(port_mapping)
        fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "CDKFargateService",
            cluster=cluster,
            task_definition=task_definition,
        )

        core.CfnOutput(
            self,
            "CDKFargateLoadBalancerDNS",
            value=fargate_service.load_balancer.load_balancer_dns_name,
        )
示例#12
0
    def __init__(self, scope: core.Stack, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        self.base_platform = BasePlatform(self, self.stack_name)

        self.task_image = aws_ecs_patterns.ApplicationLoadBalancedTaskImageOptions(
            image=aws_ecs.ContainerImage.from_registry(
                "adam9098/ecsdemo-capacityproviders:latest"),
            container_port=5000,
        )

        self.load_balanced_service = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "FargateCapacityProviderService",
            service_name='ecsdemo-capacityproviders-fargate',
            cluster=self.base_platform.ecs_cluster,
            cpu=256,
            memory_limit_mib=512,
            desired_count=10,
            public_load_balancer=True,
            task_image_options=self.task_image,
            platform_version=aws_ecs.FargatePlatformVersion.VERSION1_4)

        # This should work, but the default child is not the service cfn, it's a list of cfn service and sec group
        #self.cfn_resource = self.load_balanced_service.service.node.default_child
        self.cfn_resource = self.load_balanced_service.service.node.children[0]

        self.cfn_resource.add_deletion_override("Properties.LaunchType")

        self.load_balanced_service.task_definition.add_to_task_role_policy(
            aws_iam.PolicyStatement(
                actions=['ecs:ListTasks', 'ecs:DescribeTasks'],
                resources=['*']))
示例#13
0
    def __init__(self,
                 scope: core.Construct,
                 id: str,
                 vpc: ec2.Vpc,
                 repository: ecr.Repository,
                 shared_context: Dict[str, Any],
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.vpc = vpc

        self.model_bucket = s3.Bucket.from_bucket_name(scope=self,
                                                       id=f'{id}-model-bucket',
                                                       bucket_name=shared_context['model_bucket_name'])

        self.ecs_cluster = ecs.Cluster(self,
                                       id=f'{id}-ecs',
                                       cluster_name='serving-ecs',
                                       vpc=self.vpc,
                                       container_insights=True)

        self.task_definition = ecs.FargateTaskDefinition(self,
                                                         id=f'{id}-ecs-task-definition',
                                                         memory_limit_mib=shared_context['fargate_memory_limit_mb'],
                                                         cpu=shared_context['fargate_cpu_units'])

        self.task_definition.add_to_task_role_policy(iam.PolicyStatement(
            actions=['s3:getObject'],
            effect=iam.Effect.ALLOW,
            resources=[self.model_bucket.bucket_arn, self.model_bucket.bucket_arn + '/*']
        ))

        image = ecs.ContainerImage.from_ecr_repository(repository, 'latest')

        log_driver = ecs.AwsLogDriver(
            stream_prefix=id,
            log_retention=logs.RetentionDays.FIVE_DAYS
        )

        environment = {
            'MODEL_BUCKET_NAME': shared_context['model_bucket_name']
        }

        app_container = self.task_definition.add_container(id=f'{id}-container',
                                                           image=image,
                                                           logging=log_driver,
                                                           environment=environment)

        app_container.add_port_mappings(PortMapping(container_port=shared_context['port'],
                                                    host_port=shared_context['port']))

        self.service = ecs_patterns.ApplicationLoadBalancedFargateService(self,
                                                                          id=f'{id}-fargate-service',
                                                                          assign_public_ip=True,
                                                                          cluster=self.ecs_cluster,
                                                                          desired_count=1,
                                                                          task_definition=self.task_definition,
                                                                          open_listener=True,
                                                                          listener_port=shared_context['port'],
                                                                          target_protocol=ApplicationProtocol.HTTP)
示例#14
0
    def __init__(self, scope: core.Stack, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        self.base_platform = BasePlatform(self, self.stack_name)

        self.fargate_task_image = aws_ecs_patterns.ApplicationLoadBalancedTaskImageOptions(
            image=aws_ecs.ContainerImage.from_registry(
                "brentley/ecsdemo-frontend"),
            container_port=3000,
            environment={
                "CRYSTAL_URL": "http://ecsdemo-crystal.service:3000/crystal",
                "NODEJS_URL": "http://ecsdemo-nodejs.service:3000"
            },
        )

        self.fargate_load_balanced_service = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "FrontendFargateLBService",
            cluster=self.base_platform.ecs_cluster,
            cpu=256,
            memory_limit_mib=512,
            desired_count=1,
            public_load_balancer=True,
            cloud_map_options=self.base_platform.sd_namespace,
            task_image_options=self.fargate_task_image)

        self.fargate_load_balanced_service.service.connections.allow_to(
            self.base_platform.services_sec_grp,
            port_range=aws_ec2.Port(protocol=aws_ec2.Protocol.TCP,
                                    string_representation="frontendtobackend",
                                    from_port=3000,
                                    to_port=3000))
示例#15
0
    def __init__(self, scope, id, cluster: ecs.Cluster,
                 tracks_table: dynamodb.Table, processing_queue: sqs.Queue,
                 upload_bucket: s3.Bucket, **kwargs):
        super().__init__(scope, id, **kwargs)

        api_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'api'))

        self.api = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            'http-api-service',
            cluster=cluster,
            task_image_options=ecs_patterns.
            ApplicationLoadBalancedTaskImageOptions(
                image=ecs.ContainerImage.from_asset(directory=api_dir),
                container_port=8080,
                environment={
                    'PROCESSING_QUEUE_URL': processing_queue.queue_url,
                    'TRACKS_TABLE_NAME': tracks_table.table_name,
                    'UPLOAD_BUCKET_NAME': upload_bucket.bucket_name
                }),
            desired_count=2,
            cpu=256,
            memory_limit_mib=512)

        processing_queue.grant_send_messages(
            self.api.service.task_definition.task_role)
        tracks_table.grant_read_write_data(
            self.api.service.task_definition.task_role)
        upload_bucket.grant_put(self.api.service.task_definition.task_role)
示例#16
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        _myVpc = _ec2.Vpc(self, "myVpcID", max_azs=2, nat_gateways=1)
        _ecs_cluster_2 = _ecs.Cluster(self,
                                      'cdkFargateCluster',
                                      vpc=_myVpc,
                                      cluster_name="CdkFargate_Cluser_2")
        _UI_SERVICE = 'thiethaa/alc-autobots-ui:latest'

        # ecr.amazonaws.com
        # ecs-tasks.amazonaws.com
        # ecs.amazonaws.com

        _container_image = _ecs.ContainerImage.from_registry(_UI_SERVICE)
        _task_role = _iam.Role(
            self,
            "taskExeRoleID",
            # role_name="ecsTaskExecutionRole",
            assumed_by=_iam.ServicePrincipal(
                service='ecs-tasks.amazonaws.com'))

        alb_task_image_options = _ecs_patterns.ApplicationLoadBalancedTaskImageOptions(
            # "taskImageOptions",
            image=_container_image,
            container_port=4040,
            container_name="autobots-UI-container",
            task_role=_task_role,
            enable_logging=True)

        # A Fargate service running on an ECS cluster fronted by an application load balancer
        app_load_balanced_fargate_service = _ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            'FargateServiceALB',
            cpu=256,
            memory_limit_mib=512,
            cluster=_ecs_cluster_2,
            desired_count=1,
            # listener_port=4040,
            open_listener=True,
            min_healthy_percent=0,
            protocol=elb.ApplicationProtocol.HTTP,
            service_name='autobots_ui',
            task_image_options=alb_task_image_options)

        # app_load_balanced_fargate_service.task_definition.execution_role.role_name("ecsTaskExecutionRole")

        app_load_balancer_dns_name = app_load_balanced_fargate_service.load_balancer.load_balancer_dns_name

        alb_cfn_output = core.CfnOutput(
            self,
            "albDNSName",
            value=F"{app_load_balancer_dns_name}",
            description="Application load balancer DNS Name for autobots UI")
        listener_output = core.CfnOutput(
            self,
            "albListener",
            value=F"{app_load_balanced_fargate_service.listener}",
            description="app_load_balanced_fargate_service.listener")
示例#17
0
    def __init__(self, scope: core.Construct, id: str, custom_vpc,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        fargate_cluster = _ecs.Cluster(self,
                                       "fargateClusterId",
                                       vpc=custom_vpc)

        # Export resource name. You can import in another stack if required
        core.CfnOutput(self,
                       "ClusterNameOutput",
                       value=f"{fargate_cluster.cluster_name}",
                       export_name="ClusterName")

        weather_svc_task_def = _ecs.FargateTaskDefinition(
            self, "weatherTaskDefId")

        weather_container = weather_svc_task_def.add_container(
            "weatherContainer",
            environment={'PLATFORM': 'Mystikal Fargate World :-)'},
            image=_ecs.ContainerImage.from_registry(
                "mystique/predict-attire-for-weather"),
            memory_limit_mib=256,
            cpu=256,
            entry_point=[
                "gunicorn", "--bind", "0.0.0.0:80", "--bind", "0.0.0.0:443",
                "wsgi:application", "--access-logfile", "-", "--error-logfile",
                "-", "--capture-output", "--enable-stdio-inheritance"
            ],
            logging=_ecs.LogDrivers.aws_logs(stream_prefix="Mystique"))

        weather_container.add_port_mappings(
            _ecs.PortMapping(container_port=80))
        weather_container.add_port_mappings(
            _ecs.PortMapping(container_port=443))

        weather_service = _ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "weatherServiceId",
            cluster=fargate_cluster,
            task_definition=weather_svc_task_def,
            assign_public_ip=False,
            public_load_balancer=True,
            listener_port=80,
            desired_count=2,
            cpu=256,
            memory_limit_mib=512,
            service_name="weatherService",
        )

        # Export resource name. You can import in another stack if required
        core.CfnOutput(
            self,
            "WeatherServiceUrl",
            value=
            f"http://{weather_service.load_balancer.load_balancer_dns_name}")
        """
示例#18
0
 def airflow_web_service(self, environment):
     service_name = get_webserver_service_name(self.deploy_env)
     family = get_webserver_taskdef_family_name(self.deploy_env)
     task_def = ecs.FargateTaskDefinition(self,
                                          family,
                                          cpu=512,
                                          memory_limit_mib=1024,
                                          family=family)
     task_def.add_container(f"WebWorker-{self.deploy_env}",
                            image=self.image,
                            environment=environment,
                            secrets=self.secrets,
                            logging=ecs.LogDrivers.aws_logs(
                                stream_prefix=family,
                                log_retention=RetentionDays.ONE_DAY))
     task_def.default_container.add_port_mappings(
         ecs.PortMapping(container_port=8080,
                         host_port=8080,
                         protocol=ec2.Protocol.TCP))
     # we want only 1 instance of the web server so when new versions are deployed max_healthy_percent=100
     # you have to manually stop the current version and then it should start a new version - done by deploy task
     lb_security_group = ec2.SecurityGroup(
         self, f"lb-sec-group-{self.deploy_env}", vpc=self.vpc)
     service = ecs_patterns.ApplicationLoadBalancedFargateService(
         self,
         service_name,
         cluster=self.cluster,  # Required
         service_name=service_name,
         platform_version=ecs.FargatePlatformVersion.VERSION1_4,
         cpu=512,  # Default is 256
         desired_count=1,  # Default is 1
         task_definition=task_def,
         memory_limit_mib=2048,  # Default is 512
         public_load_balancer=True,
         security_groups=[lb_security_group],
         certificate=Certificate.from_certificate_arn(
             self,
             f"lb-cert-{self.deploy_env}",
             certificate_arn=self.config["lb_certificate_arn"]),
         max_healthy_percent=100)
     service.target_group.configure_health_check(path="/health")
     # restrict access to the load balancer to only VPN
     lb_security_group.connections.allow_from(
         ec2.Peer.ipv4(self.config["lb_vpn_addresses"]), ec2.Port.tcp(443))
     # configure DNS alias for the load balancer
     route53.ARecord(self,
                     f"lb-record-{self.deploy_env}",
                     zone=route53.HostedZone.from_hosted_zone_attributes(
                         self,
                         f"Zone-{self.deploy_env}",
                         zone_name=f"Zone-{self.deploy_env}",
                         hosted_zone_id=self.config["route53_zone_id"]),
                     record_name=self.config["lb_dns_name"],
                     target=route53.RecordTarget.from_alias(
                         targets.LoadBalancerTarget(service.load_balancer)))
     return service
示例#19
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Get the hosted Zone and create a certificate for our domain

        hosted_zone = route53.HostedZone.from_hosted_zone_attributes(
            self,
            "HostedZone",
            hosted_zone_id=HOSTED_ZONE_ID,
            zone_name=HOSTED_ZONE_NAME,
        )

        cert = certificatemanager.DnsValidatedCertificate(
            self,
            "Certificate",
            hosted_zone=hosted_zone,
            domain_name=APP_DNS_NAME)

        # Set up a new VPC

        vpc = ec2.Vpc(self, "med-qaid-vpc", max_azs=2)

        # Set up an ECS Cluster for fargate

        cluster = ecs.Cluster(self, "med-qaid-cluster", vpc=vpc)

        # Define the Docker Image for our container (the CDK will do the build and push for us!)
        docker_image = ecr_assets.DockerImageAsset(
            self,
            "med-qaid-app",
            directory=os.path.join(os.path.dirname(__file__), "..", "src"),
        )

        # Define the fargate service + ALB

        fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "FargateService",
            cluster=cluster,
            certificate=cert,
            domain_name=f"{APP_DNS_NAME}",
            domain_zone=hosted_zone,
            cpu=2048,
            memory_limit_mib=16384,
            task_image_options={
                "image":
                ecs.ContainerImage.from_docker_image_asset(docker_image),
                "environment": {
                    "PORT": "80",
                },
            },
        )

        # Allow 10 seconds for in flight requests before termination, the default of 5 minutes is much too high.
        fargate_service.target_group.set_attribute(
            key="deregistration_delay.timeout_seconds", value="10")
    def __init__(self, scope: core.Construct, id: str, cluster_configuration,
                 **kwargs) -> None:

        super().__init__(scope, id, **kwargs)
        self.cluster_configuration = cluster_configuration

        cluster_vpc = aws_ec2.Vpc(
            self,
            "ClusterVPC",
            cidr="10.0.0.0/16",
            nat_gateways=1,
        )

        core.Tags.of(cluster_vpc).add(
            "Name", cluster_configuration['cluster_name'] + "VPC")

        cluster = aws_ecs.Cluster(
            self,
            "ECSCluster",
            cluster_name=cluster_configuration['cluster_name'],
            vpc=cluster_vpc)

        if self.cluster_configuration['fargate_enabled'] is True:
            aws_ecs_patterns.ApplicationLoadBalancedFargateService(
                self,
                "ECSFargateService",
                service_name=cluster_configuration['cluster_name'] + "Service",
                cluster=cluster,  # Required
                cpu=cluster_configuration["container_cpu"],  # Default is 256
                desired_count=cluster_configuration["container_desired_count"],
                task_image_options=aws_ecs_patterns.
                ApplicationLoadBalancedTaskImageOptions(
                    image=aws_ecs.ContainerImage.from_registry(
                        cluster_configuration["container_image"]),
                    container_port=cluster_configuration["container_port"]),
                memory_limit_mib=cluster_configuration[
                    "container_mem"],  # Default is 512
                public_load_balancer=True)  # Default is False
        else:
            aws_ecs_patterns.ApplicationLoadBalancedEc2Service(
                self,
                "ECSFargateService",
                service_name=cluster_configuration['cluster_name'] + "Service",
                cluster=cluster,  # Required
                cpu=cluster_configuration["container_cpu"],  # Default is 256
                desired_count=cluster_configuration["container_desired_count"],
                task_image_options=aws_ecs_patterns.
                ApplicationLoadBalancedTaskImageOptions(
                    image=aws_ecs.ContainerImage.from_registry(
                        cluster_configuration["container_image"]),
                    container_port=cluster_configuration["container_port"]),
                memory_limit_mib=cluster_configuration[
                    "container_mem"],  # Default is 512
                public_load_balancer=True)  # Default is False
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here

        vpc = ec2.Vpc(
            self,
            "MyVpc",
            max_azs=3,
        )

        cluster = ecs.Cluster(self, 'Ec2Cluster', vpc=vpc)

        fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "FargateService",
            cluster=cluster,
            cpu=256,
            desired_count=1,
            task_image_options=ecs_patterns.
            ApplicationLoadBalancedTaskImageOptions(
                image=ecs.ContainerImage.from_asset(
                    os.path.join(dirname, "..", "image")),
                container_port=3000),
            memory_limit_mib=512,
            public_load_balancer=True,
            listener_port=80)

        fargate_service.service.connections.security_groups[
            0].add_ingress_rule(peer=ec2.Peer.ipv4(vpc.vpc_cidr_block),
                                connection=ec2.Port.tcp(80),
                                description="Allow http inbound from VPC")

        fargate_service.target_group.configure_health_check(path="/login")

        distribution = cloudfront.Distribution(
            self,
            "myDist",
            default_behavior={
                "origin":
                origins.LoadBalancerV2Origin(
                    fargate_service.load_balancer,
                    protocol_policy=cloudfront.OriginProtocolPolicy(
                        "HTTP_ONLY"))
            })

        core.CfnOutput(
            self,
            "LoadBalancerDNS",
            value=fargate_service.load_balancer.load_balancer_dns_name)

        core.CfnOutput(self,
                       "CloudFrontDistributionDNS",
                       value=distribution.domain_name)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create the ECR Repository
        ecr_repository = ecr.Repository(self,
                                        "ecs-devops-sandbox-repository",
                                        repository_name="ecs-devops-sandbox-repository")

        # Create the ECS Cluster (and VPC)
        vpc = ec2.Vpc(self,
                      "ecs-devops-sandbox-vpc",
                      max_azs=3)
        cluster = ecs.Cluster(self,
                              "ecs-devops-sandbox-cluster",
                              cluster_name="ecs-devops-sandbox-cluster",
                              vpc=vpc)

        # Create the ECS Task Definition with placeholder container (and named Task Execution IAM Role)
        execution_role = iam.Role(self,
                                  "ecs-devops-sandbox-execution-role",
                                  assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
                                  role_name="ecs-devops-sandbox-execution-role")
        execution_role.add_to_policy(iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            resources=["*"],
            actions=[
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
                ]
        ))
        task_definition = ecs.FargateTaskDefinition(self,
                                                    "ecs-devops-sandbox-task-definition",
                                                    execution_role=execution_role,
                                                    family="ecs-devops-sandbox-task-definition")

        container = task_definition.add_container(
            "ecs-devops-sandbox",
            image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
        )

        port_mapping = ecs.PortMapping(container_port=5000)
        container.add_port_mappings(port_mapping)


        # Create a load balanced ECS Service
        # Athough this block works, I was not able to
        load_balanced_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "ecs-devops-sandbox-service",
            cluster=cluster,
            task_definition=task_definition,
            service_name="ecs-devops-sandbox-service")
示例#23
0
    def __init__(self, scope: core.Construct, construct_id: str, cluster, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        ecsPatterns.ApplicationLoadBalancedFargateService(self, "nginx",
                                                          cluster=cluster,
                                                          memory_limit_mib=1024,
                                                          cpu=512,
                                                          task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
                                                              image=ecs.ContainerImage.from_registry("nginx:stable"),
                                                          )
                                                          )
示例#24
0
 def _create_service(self, cluster: ecs.Cluster):
     """
     This defines and creates the services where
     our web application will be deployed in.
     """
     return ecs_patterns.ApplicationLoadBalancedFargateService(
         self,
         'Service',
         vpc=cluster.ecsCluster.vpc,
         task_image_options={
             'image': ecs.ContainerImage.from_asset('./web')
         })
示例#25
0
    def __init__(self, scope: cdk.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        ecsp.ApplicationLoadBalancedFargateService(
            self,
            "MyWebServer",
            task_image_options=ecsp.ApplicationLoadBalancedTaskImageOptions(
                # image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")),
                image=ecs.ContainerImage.from_registry(
                    "public.ecr.aws/f0e4c8e7/nginx-test:latest")),
            public_load_balancer=True)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        self.wordpress_lb_service = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "WordPressALBService",
            cpu=512,
            memory_limit_mib=1024,
            listener_port=80,
            task_image_options=aws_ecs_patterns.
            ApplicationLoadBalancedTaskImageOptions(
                image=aws_ecs.ContainerImage.from_registry('wordpress:latest'),
                container_port=8080))
    def __init__(self, scope: core.Stack, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        self.base_platform = BasePlatform(self, self.stack_name)

        self.fargate_task_image = aws_ecs_patterns.ApplicationLoadBalancedTaskImageOptions(
            image=aws_ecs.ContainerImage.from_registry(
                "adam9098/ecsdemo-frontend"),
            container_port=3000,
            environment={
                "CRYSTAL_URL": "http://ecsdemo-crystal.service:3000/crystal",
                "NODEJS_URL": "http://ecsdemo-nodejs.service:3000",
                "REGION": getenv('AWS_DEFAULT_REGION')
            },
        )

        self.fargate_load_balanced_service = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "FrontendFargateLBService",
            service_name='ecsdemo-frontend',
            cluster=self.base_platform.ecs_cluster,
            cpu=256,
            memory_limit_mib=512,
            desired_count=3,
            public_load_balancer=True,
            cloud_map_options=self.base_platform.sd_namespace,
            task_image_options=self.fargate_task_image)

        self.fargate_load_balanced_service.task_definition.add_to_task_role_policy(
            aws_iam.PolicyStatement(actions=['ec2:DescribeSubnets'],
                                    resources=['*']))

        self.fargate_load_balanced_service.service.connections.allow_to(
            self.base_platform.services_sec_grp,
            port_range=aws_ec2.Port(protocol=aws_ec2.Protocol.TCP,
                                    string_representation="frontendtobackend",
                                    from_port=3000,
                                    to_port=3000))

        # Enable Service Autoscaling
        self.autoscale = self.fargate_load_balanced_service.service.auto_scale_task_count(
            min_capacity=1, max_capacity=10)

        self.autoscale.scale_on_cpu_utilization(
            "CPUAutoscaling",
            target_utilization_percent=50,
            scale_in_cooldown=core.Duration.seconds(30),
            scale_out_cooldown=core.Duration.seconds(30))
示例#28
0
 def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
     super().__init__(scope, id, **kwargs)
     vpc = ec2.Vpc(self, "MyVpc", max_azs=3)  # default is all AZs in region
     cluster = ecs.Cluster(self, "MyCluster", vpc=vpc)
     ecs_patterns.ApplicationLoadBalancedFargateService(
         self,
         "MyFargateService",
         cluster=cluster,  # Required
         cpu=512,  # Default is 256
         desired_count=6,  # Default is 1
         task_image_options=ecs_patterns.
         ApplicationLoadBalancedTaskImageOptions(
             image=ecs.ContainerImage.from_registry(
                 "amazon/amazon-ecs-sample")),
         memory_limit_mib=2048,  # Default is 512
         public_load_balancer=False)  # Default is False
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #vpc
        chat_app_vpc = aws_ec2.Vpc(self,
                                   "ChatAppVpc",
                                   max_azs=2,
                                   nat_gateways=1)

        #fargate cluster
        chat_app_cluster = aws_ecs.Cluster(self, "ChatAppCluster")

        #fargate task definition
        chat_app_fg_def = aws_ecs.FargateTaskDefinition(
            self, "ChatAppTaskDefinition")

        #container definition
        chat_app_container = chat_app_fg_def.add_container(
            "ChatAppContainer",
            image=aws_ecs.ContainerImage.from_registry(
                "manuja/chat-app:latest"),
            environment={"github": "https://github.com/manujakau"})

        #port mapping to container
        chat_app_container.add_port_mappings(
            aws_ecs.PortMapping(container_port=3000,
                                protocol=aws_ecs.Protocol.TCP))

        #attached load balancer
        chat_app_alb = aws_ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "ChatAppALB",
            cluster=chat_app_cluster,
            task_definition=chat_app_fg_def,
            assign_public_ip=False,
            public_load_balancer=True,
            listener_port=80,
            desired_count=1,
            service_name="ServerlessChatApp")

        #output
        chat_app_output = core.CfnOutput(
            self,
            "chatappoutput",
            value=f"http://{chat_app_alb.load_balancer.load_balancer_dns_name}",
            description="Chat app url")
    def __init__(self, scope: core.Construct, id: str, custom_vpc,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        fargate_cluster = _ecs.Cluster(self,
                                       "fargateClusterId",
                                       vpc=custom_vpc)

        core.CfnOutput(self,
                       "ClusterNameOutput",
                       value=f"{fargate_cluster.cluster_name}",
                       export_name="ClusterName")
        """
        Service running chat service
        """

        chat_app_task_def = _ecs.FargateTaskDefinition(self, "chatAppTaskDef")

        chat_app_container = chat_app_task_def.add_container(
            "chatAppContainer",
            environment={'github': 'https://github.com/miztiik'},
            image=_ecs.ContainerImage.from_registry(
                "mystique/fargate-chat-app:latest"),
            logging=_ecs.LogDrivers.aws_logs(stream_prefix="Mystique"))

        chat_app_container.add_port_mappings(
            _ecs.PortMapping(container_port=3000, protocol=_ecs.Protocol.TCP))

        chat_app_service = _ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "chatAppServiceId",
            cluster=fargate_cluster,
            task_definition=chat_app_task_def,
            assign_public_ip=False,
            public_load_balancer=True,
            listener_port=80,
            desired_count=1,
            # cpu=1024,
            # memory_limit_mib=2048,
            # service_name="chatAppService",
        )
        core.CfnOutput(
            self,
            "chatAppServiceUrl",
            value=
            f"http://{chat_app_service.load_balancer.load_balancer_dns_name}")