Ejemplo n.º 1
0
    def configure_load_balancers(self, vpc: ec2.Vpc, publoadbal: elbv2.ApplicationLoadBalancer):
        tgroups = {}
        hc = elbv2.HealthCheck()
        hc['intervalSecs'] = 10
        hc['protocol'] = elbv2.ApplicationProtocol.Http
        hc['healthyThresholdCount'] = 10
        hc['unhealthyThresholdCount'] = 10
        hc['timeoutSeconds'] = 5
        hc['path'] = '/'

        targetgroups = [
            {'name': 'grafana', 'httpcode': '302', 'port': 3000},
            {'name': 'prometheus', 'httpcode': '405', 'port': 9090},
            {'name': 'colorgateway', 'httpcode': '200', 'port': 9080}]

        for tgs in targetgroups:
            tgname = tgs['name']
            code = tgs['httpcode']
            port = tgs['port']
            hc['healthyHttpCodes'] = code

            atg = elbv2.ApplicationTargetGroup(self, id=tgname + 'TargetGroup', protocol=elbv2.ApplicationProtocol.Http,
                                               port=port, deregistration_delay_sec=30, vpc=vpc,
                                               target_group_name='appmeshdemo-' + tgname + '-1', health_check=hc,
                                               target_type=elbv2.TargetType.Ip)

            lbl = elbv2.ApplicationListener(self, tgname + 'LoadBalancerListener', port=port,
                                            protocol=elbv2.ApplicationProtocol.Http, default_target_groups=[atg],
                                            load_balancer=publoadbal)

            elbv2.ApplicationListenerRule(self, tgname + 'LoadBalancerRule', listener=lbl,
                                          target_groups=[atg], priority=1, path_pattern='*')

            tgroups[tgname] = atg


        return tgroups
Ejemplo n.º 2
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here

        # Create a VPC
        myvpc = ec2.Vpc(self, "CDKVPC", cidr=vars.cidr)

        # SG for ELB creation
        websitefrontendSG = ec2.SecurityGroup(
            self,
            'websitefrontendSG',
            vpc=myvpc,
            security_group_name='websitefrontendSG')
        websitefrontendSG.add_ingress_rule(peer=ec2.Peer.ipv4('0.0.0.0/0'),
                                           connection=ec2.Port.tcp(80))
        websitefrontendSG.add_ingress_rule(peer=ec2.Peer.ipv4('0.0.0.0/0'),
                                           connection=ec2.Port.tcp(443))

        # Create ALB in VPC
        alb = elb.ApplicationLoadBalancer(
            self,
            'websitefrontend-public',
            vpc=myvpc,
            load_balancer_name='websitefrontend-public',
            security_group=websitefrontendSG,
            internet_facing=True)

        # Add target group to ALB
        catalogtargetgroup = elb.ApplicationTargetGroup(
            self,
            'CatalogTargetGroup',
            port=80,
            vpc=myvpc,
            target_type=elb.TargetType.IP)

        if not vars.sslcert:
            # Add http listener to ALB
            alblistenerhttp = elb.ApplicationListener(
                self,
                'alblistenerhttp',
                load_balancer=alb,
                default_target_groups=[catalogtargetgroup],
                port=80)

        if vars.sslcert:
            # Add http listener to ALB
            alblistenerhttp = elb.ApplicationListener(self,
                                                      'alblistenerhttp',
                                                      load_balancer=alb,
                                                      port=80)
            elb.ApplicationListenerRule(self,
                                        'httpredirectionrule',
                                        listener=alblistenerhttp,
                                        redirect_response=elb.RedirectResponse(
                                            status_code='HTTP_301',
                                            port='443',
                                            protocol='HTTPS'))
            # OPTIONAL - Add https listener to ALB & attach certificate
            alblistenerhttps = elb.ApplicationListener(
                self,
                'alblistenerhttps',
                load_balancer=alb,
                default_target_groups=[catalogtargetgroup],
                port=443,
                certificate_arns=[vars.sslcert_arn])

            # OPTIONAL - Redirect HTTP to HTTPS
            alblistenerhttp.add_redirect_response(id='redirectionrule',
                                                  port='443',
                                                  status_code='HTTP_301',
                                                  protocol='HTTPS')

        if vars.customdomain:
            # OPTIONAL - Update DNS with ALB
            webshopxyz_zone = r53.HostedZone.from_hosted_zone_attributes(
                self,
                id='customdomain',
                hosted_zone_id=vars.hosted_zone_id,
                zone_name=vars.zone_name)
            webshop_root_record = r53.ARecord(
                self,
                'ALBAliasRecord',
                zone=webshopxyz_zone,
                target=r53.RecordTarget.from_alias(
                    alias.LoadBalancerTarget(alb)))

        # SG for ECS creation
        ECSSG = ec2.SecurityGroup(self,
                                  'ECSSecurityGroup',
                                  vpc=myvpc,
                                  security_group_name='ECS')
        ECSSG.add_ingress_rule(peer=websitefrontendSG,
                               connection=ec2.Port.tcp(80))

        # SG for MySQL creation
        MySQLSG = ec2.SecurityGroup(self,
                                    'DBSecurityGroup',
                                    vpc=myvpc,
                                    security_group_name='DB')
        MySQLSG.add_ingress_rule(peer=ECSSG, connection=ec2.Port.tcp(3306))

        # Create DB subnet group
        subnetlist = []
        for subnet in myvpc.private_subnets:
            subnetlist.append(subnet.subnet_id)
        subnetgr = rds.CfnDBSubnetGroup(
            self,
            'democlustersubnetgroup',
            db_subnet_group_name='democlustersubnetgroup',
            db_subnet_group_description='DemoCluster',
            subnet_ids=subnetlist)

        # Create secret db passwd
        secret = sm.SecretStringGenerator(
            exclude_characters="\"'@/\\",
            secret_string_template='{"username": "******"}',
            generate_string_key='password',
            password_length=40)
        dbpass = sm.Secret(self,
                           'democlusterpass',
                           secret_name='democlusterpass',
                           generate_secret_string=secret)

        # Create Aurora serverless MySQL instance
        dbcluster = rds.CfnDBCluster(
            self,
            'DemoCluster',
            engine='aurora',
            engine_mode='serverless',
            engine_version='5.6',
            db_cluster_identifier='DemoCluster',
            master_username=dbpass.secret_value_from_json(
                'username').to_string(),
            master_user_password=dbpass.secret_value_from_json(
                'password').to_string(),
            storage_encrypted=True,
            port=3306,
            vpc_security_group_ids=[MySQLSG.security_group_id],
            scaling_configuration=rds.CfnDBCluster.
            ScalingConfigurationProperty(auto_pause=True,
                                         max_capacity=4,
                                         min_capacity=1,
                                         seconds_until_auto_pause=300),
            db_subnet_group_name=subnetgr.db_subnet_group_name)
        dbcluster.add_override('DependsOn', 'democlustersubnetgroup')

        # Attach database to secret
        attach = sm.CfnSecretTargetAttachment(
            self,
            'RDSAttachment',
            secret_id=dbpass.secret_arn,
            target_id=dbcluster.ref,
            target_type='AWS::RDS::DBCluster')

        # Upload image into ECR repo
        ecrdemoimage = ecra.DockerImageAsset(self,
                                             'ecrdemoimage',
                                             directory='../',
                                             repository_name='demorepo',
                                             exclude=['cdk.out'])

        # Create ECS fargate cluster
        ecscluster = ecs.Cluster(self, "ecsCluster", vpc=myvpc)

        # Create task role for productsCatalogTask
        getsecretpolicystatement = iam.PolicyStatement(actions=[
            "secretsmanager:GetResourcePolicy",
            "secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret",
            "secretsmanager:ListSecretVersionIds"
        ],
                                                       resources=[
                                                           dbpass.secret_arn
                                                       ],
                                                       effect=iam.Effect.ALLOW)
        getsecretpolicydocument = iam.PolicyDocument(
            statements=[getsecretpolicystatement])
        taskrole = iam.Role(
            self,
            'TaskRole',
            assumed_by=iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
            role_name='TaskRoleforproductsCatalogTask',
            inline_policies=[getsecretpolicydocument])

        # Create task definition
        taskdefinition = ecs.FargateTaskDefinition(self,
                                                   'productsCatalogTask',
                                                   cpu=1024,
                                                   memory_limit_mib=2048,
                                                   task_role=taskrole)

        # Add container to task definition
        productscatalogcontainer = taskdefinition.add_container(
            'productscatalogcontainer',
            image=ecs.ContainerImage.from_docker_image_asset(
                asset=ecrdemoimage),
            environment={
                "region": vars.region,
                "secretname": "democlusterpass"
            })
        productscatalogcontainer.add_port_mappings(
            ecs.PortMapping(container_port=80, host_port=80))

        # Create service and associate it with the cluster
        catalogservice = ecs.FargateService(
            self,
            'catalogservice',
            task_definition=taskdefinition,
            assign_public_ip=False,
            security_group=ECSSG,
            vpc_subnets=ec2.SubnetSelection(subnets=myvpc.select_subnets(
                subnet_type=ec2.SubnetType.PRIVATE).subnets),
            cluster=ecscluster,
            desired_count=2)

        # Add autoscaling to the service
        scaling = catalogservice.auto_scale_task_count(max_capacity=20,
                                                       min_capacity=1)
        scaling.scale_on_cpu_utilization(
            'ScaleOnCPU',
            target_utilization_percent=70,
            scale_in_cooldown=core.Duration.seconds(amount=1),
            scale_out_cooldown=core.Duration.seconds(amount=0))

        # Associate the fargate service with load balancer targetgroup
        catalogservice.attach_to_application_target_group(catalogtargetgroup)
Ejemplo n.º 3
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Set up VPC
        vpc = ec2.Vpc(self, 'CDKVPC', cidr=config['cidr'])

        # SG for ELB
        webSG = ec2.SecurityGroup(self,
                                  'webSG',
                                  vpc=vpc,
                                  security_group_name='WebSG')
        webSG.add_ingress_rule(peer=ec2.Peer.ipv4('0.0.0.0/0'),
                               connection=ec2.Port.tcp(80))
        webSG.add_ingress_rule(peer=ec2.Peer.ipv4('0.0.0.0/0'),
                               connection=ec2.Port.tcp(443))

        # Create ALB
        alb = elb.ApplicationLoadBalancer(self,
                                          'webALB-public',
                                          vpc=vpc,
                                          load_balancer_name='webALB-public',
                                          security_group=webSG,
                                          internet_facing=True)

        # Add listener at port 80 with default action
        alblistener = alb.add_listener(
            'webALB-Listener',
            port=80,
            open=True,
            default_action=elb.ListenerAction.fixed_response(
                status_code=200,
                content_type='text/plain',
                message_body='default action'))

        # SG for ECS Fargate
        fargateSG = ec2.SecurityGroup(self,
                                      'fargateSG',
                                      vpc=vpc,
                                      security_group_name='FargateSG')
        fargateSG.add_ingress_rule(peer=webSG, connection=ec2.Port.tcp(80))
        fargateSG.add_ingress_rule(peer=fargateSG, connection=ec2.Port.tcp(80))

        # Create fargate cluster
        fargate_cluster = ecs.Cluster(
            self,
            'FargateCluster',
            vpc=vpc,
            cluster_name='FargateCluster',
        )

        # Set up service discovery
        namespace = sd.PrivateDnsNamespace(
            self,
            'PrivateDNSNamespace',
            name=config['service_discovery_namespace'],
            vpc=vpc)

        # Create fargate resources for each microservice
        for indx, s in enumerate(config['services']):

            # Create task definition and add the container from the repo
            task_definition = ecs.FargateTaskDefinition(
                self,
                'ServiceTaskDefinition' + str(indx),
                cpu=1024,
                memory_limit_mib=2048)
            cont = task_definition.add_container(
                'ServiceContainer' + str(indx),
                image=ecs.ContainerImage.from_registry(s['repo']),
                environment={"REGION": config['region']})
            cont.add_port_mappings(
                ecs.PortMapping(container_port=80, host_port=80))

            # Create service in private subnets
            service = ecs.FargateService(
                self,
                'ServiceFargateService' + str(indx),
                task_definition=task_definition,
                assign_public_ip=False,
                security_group=fargateSG,
                vpc_subnets=ec2.SubnetSelection(subnets=vpc.select_subnets(
                    subnet_type=ec2.SubnetType.PRIVATE).subnets),
                cluster=fargate_cluster,
                desired_count=s['num_tasks'])
            service.enable_cloud_map(cloud_map_namespace=namespace,
                                     dns_record_type=sd.DnsRecordType.SRV,
                                     name=s['service_discovery_service_name'])

            # Set up ALB target group and set Fargate service as target
            target_group = elb.ApplicationTargetGroup(
                self,
                'ServiceTargetGroup' + str(indx),
                port=80,
                vpc=vpc,
                target_type=elb.TargetType.IP,
                target_group_name=s['service_name'] + 'TargetGroup',
                targets=[
                    service.load_balancer_target(
                        container_name='ServiceContainer' + str(indx),
                        container_port=80)
                ])

            # Add the path pattern rule for the listener
            alblistenerrule = elb.ApplicationListenerRule(
                self,
                'ListenerRule' + str(indx),
                path_pattern=s['alb_routing_path'],
                priority=indx + 1,
                listener=alblistener,
                target_groups=[target_group])
Ejemplo n.º 4
0
    def createResources(self, ns):

        # Attach ALB to ECS Service
        be_health_check = elbv2.HealthCheck(interval=core.Duration.seconds(60),
                                            path="/ping",
                                            timeout=core.Duration.seconds(5))

        self.bentoALB.add_redirect(
            source_protocol=elbv2.ApplicationProtocol.HTTP,
            source_port=80,
            target_protocol=elbv2.ApplicationProtocol.HTTPS,
            target_port=443)

        # Get certificate ARN for specified domain name
        client = boto3.client('acm')
        response = client.list_certificates(CertificateStatuses=[
            'ISSUED',
        ], )

        for cert in response["CertificateSummaryList"]:
            if ('*.{}'.format(self.config[ns]['domain_name'])
                    in cert.values()):
                certARN = cert['CertificateArn']

        bento_cert = cfm.Certificate.from_certificate_arn(
            self, "bento-cert", certificate_arn=certARN)

        listener = self.bentoALB.add_listener("PublicListener",
                                              certificates=[bento_cert],
                                              port=443)

        frontendtarget = listener.add_targets(
            "ECS-frontend-Target",
            port=int(self.config[ns]['frontend_container_port']),
            targets=[self.frontendService],
            target_group_name="{}-frontend".format(ns))
        core.Tags.of(frontendtarget).add("Name",
                                         "{}-frontend-alb-target".format(ns))

        backendtarget = listener.add_targets(
            "ECS-backend-Target",
            port=int(self.config[ns]['backend_container_port']),
            targets=[self.backendService],
            health_check=be_health_check,
            target_group_name="{}-backend".format(ns))
        core.Tags.of(backendtarget).add("Name",
                                        "{}-backend-alb-target".format(ns))

        # Add a fixed error message when browsing an invalid URL
        listener.add_action(
            "ECS-Content-Not-Found",
            action=elbv2.ListenerAction.fixed_response(
                200, message_body="The requested resource is not available"))

        elbv2.ApplicationListenerRule(self,
                                      id="alb_frontend_rule",
                                      path_pattern="/*",
                                      priority=1,
                                      listener=listener,
                                      target_groups=[frontendtarget])

        elbv2.ApplicationListenerRule(self,
                                      id="alb_backend_rule",
                                      path_pattern="/v1/graphql/*",
                                      priority=2,
                                      listener=listener,
                                      target_groups=[backendtarget])
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        #arn = elbv2.ApplicationListener.from_application_listener_attributes(self, "test", listener_arn=)
        # importing security Group from exesting resources
        mysg = ec2.SecurityGroup.from_security_group_id(
            self, "sg", security_group_id=data['security_grp'])

        # importting Vpc from exesting resources
        vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=data['vpc_id'])

        # creating loadbalancer woth exesting resources
        lb = elbv2.ApplicationLoadBalancer(
            self,
            "LB",
            vpc=vpc,
            security_group=mysg,
            internet_facing=True,
            load_balancer_name="myloadbalancer",
            vpc_subnets=ec2.SubnetSelection(
                availability_zones=["ap-south-1a", "ap-south-1b"],
                one_per_az=True))

        # creating Target Group1
        mytarget_group = elbv2.ApplicationTargetGroup(
            self,
            "targetGroup",
            target_group_name="mytarget-group",
            protocol=elbv2.ApplicationProtocol.HTTP,
            target_type=elbv2.TargetType.INSTANCE,
            port=80,
            vpc=vpc,
            health_check=elbv2.HealthCheck(enabled=True,
                                           healthy_http_codes="200",
                                           path="/",
                                           port="80"))

        # creating target group 2
        mytarget_group2 = elbv2.ApplicationTargetGroup(
            self,
            "targetGroup2",
            target_group_name="mytarget-group2",
            protocol=elbv2.ApplicationProtocol.HTTP,
            target_type=elbv2.TargetType.INSTANCE,
            port=80,
            vpc=vpc,
            health_check=elbv2.HealthCheck(enabled=True,
                                           healthy_http_codes="200",
                                           path="/home",
                                           port="80"))

        # adding a loadbalancer default listener
        listener = lb.add_listener("listener",
                                   port=80,
                                   default_target_groups=[mytarget_group])

        # adding loadbalancer listener Rule
        if version == "versionone":
            slect_target = mytarget_group
        else:
            slect_target = mytarget_group2

        listenerRule = elbv2.ApplicationListenerRule(
            self,
            "listenerRule",
            listener=listener,
            priority=1,
            path_pattern="/home",
            target_groups=[slect_target])

        # Output the DNS name of loadbalancer
        output_1 = core.CfnOutput(self,
                                  "mybucketoutput1",
                                  value=lb.load_balancer_dns_name,
                                  export_name="mybucketoutput1")
        core.Tag.add(lb, "Name", "naresh")