Exemplo n.º 1
0
def add_extra_certificate(listener_stack, listener, cert_arn):
    """
    Function to add Certificates to listener

    :param listener_stack: The stack that "owns" the listener.
    :param listener: The listener to add the certificate to
    :param cert_arn: The identifier of the certificate
    """
    cert_arn_re = re.compile(
        r"((?:^arn:aws(?:-[a-z]+)?:acm:[\S]+:[0-9]+:certificate/)"
        r"([a-z0-9]{8}(?:-[a-z0-9]{4}){3}-[a-z0-9]{12})$)")
    if cert_arn_re.match(cert_arn):
        cert_arn_id = cert_arn
    elif isinstance(cert_arn, str) and cert_arn.find(ACM_KEY) < 0:
        cert_arn_id = f"{ACM_KEY}::{cert_arn}"
    elif isinstance(cert_arn, str) and cert_arn.find(ACM_KEY):
        cert_arn_id = cert_arn
    else:
        raise ValueError(
            f"{listener_stack.title} - Certificate value is not valid",
            cert_arn)
    if hasattr(listener, "Certificates") and listener.Certificates:
        add_listener_certificate_via_arn(listener_stack, listener, cert_arn_id,
                                         cert_arn)
    else:
        setattr(listener, "Certificates",
                [Certificate(CertificateArn=cert_arn_id)])
 def _add_service_listener(self, service_name, target_group_action,
                           alb, internal):
     ssl_cert = Certificate(CertificateArn=self.ssl_certificate_arn)
     service_listener = Listener(
         "SslLoadBalancerListener" + service_name,
         Protocol="HTTPS",
         DefaultActions=[target_group_action],
         LoadBalancerArn=Ref(alb),
         Port=443,
         Certificates=[ssl_cert],
         SslPolicy="ELBSecurityPolicy-FS-1-2-Res-2019-08"
     )
     self.template.add_resource(service_listener)
     if internal:
         # Allow HTTP traffic on internal services
         http_service_listener = Listener(
             "LoadBalancerListener" + service_name,
             Protocol="HTTP",
             DefaultActions=[target_group_action],
             LoadBalancerArn=Ref(alb),
             Port=80
         )
         self.template.add_resource(http_service_listener)
     else:
         # Redirect HTTP to HTTPS on external services
         redirection_config = RedirectConfig(
             StatusCode='HTTP_301',
             Protocol='HTTPS',
             Port='443'
         )
         http_redirection_action = Action(
             RedirectConfig=redirection_config,
             Type="redirect"
         )
         http_redirection_listener = Listener(
             "LoadBalancerRedirectionListener" + service_name,
             Protocol="HTTP",
             DefaultActions=[http_redirection_action],
             LoadBalancerArn=Ref(alb),
             Port=80
         )
         self.template.add_resource(http_redirection_listener)
     return service_listener
Exemplo n.º 3
0
def add_listener_certificate_via_arn(listener_stack, listener,
                                     certificate_arn_id, cert_name) -> None:
    """
    Adds a new ListenerCertificate for a given listener.

    ListenerCertificate can only take 1 certificate in the list !!

    :param ecs_composex.common.stacks.ComposeXStack listener_stack:
    :param ecs_composex.elbv2.elbv2_stack.elbv2_listener.ComposeListener listener:
    :param str certificate_arn_id: the ID to point to the certificate
    :param str cert_name:

    """
    listener_stack.stack_template.add_resource(
        ListenerCertificate(
            f"AcmCert{listener.title}{NONALPHANUM.sub('', cert_name)}",
            Certificates=[Certificate(CertificateArn=certificate_arn_id)],
            ListenerArn=Ref(listener),
        ))
Exemplo n.º 4
0
def add_ssl_config_to_listeners(service_template, cert_import, ports):
    """
    Function to add the SSL settings to the listener of the LB

    :param service_template:
    :param cert_import:
    :param list ports: list of ports (int)
    :return:
    """
    for port in ports:
        if not isinstance(port, int):
            raise TypeError(f"Port must be of type", int, "got", type(port))
        listener = find_service_listener(port, service_template)
        if listener.Protocol == "HTTP":
            listener.Protocol = "HTTPS"
            setattr(
                listener,
                "Certificates",
                [Certificate(CertificateArn=cert_import)],
            )
        elif listener.Protocol == "TCP":
            listener.Protocol = "TLS"
Exemplo n.º 5
0
    def to_json(self):
        if self._json is not None:
            return self._json

        # Validity checks
        if len(self.subnet_ids) < 2:
            raise ValidationException(
                "Use .subnet_id() to specify at least two ELB subnets")
        if len(self.cert_ids) < 1:
            raise ValidationException(
                "Use .certificate_id() to specify at least one certificate")
        if not self._ecs_redirect and len(self.default_targets) < 1:
            raise ValidationException(
                "Use .default_target() to specify at least one default target or .ecs_redirect("
                ") to set up a redirect container")
        for (name, tp) in self.target_paths.iteritems():
            if len(set(map(lambda h: h.type, tp.hosts))) != 1:
                raise ValidationException(
                    "Inconsistent target types for %s. All hosts for a given path must have the "
                    "same type (ip or instance)." % name)

        # Build Security Group
        if self._custom_elb_sgs:
            elb_sgs = self._custom_elb_sgs
        else:
            elb_sg = SecurityGroup(
                "ElbSecurityGroup",
                GroupDescription=Sub("${AWS::StackName}-ElbSg"),
                Tags=self.tags_with(Name=Sub("${AWS::StackName}-ElbSg")),
                VpcId=self.vpc_id,
                SecurityGroupEgress=[
                    SecurityGroupRule(CidrIp="0.0.0.0/0", IpProtocol="-1")
                ],
                SecurityGroupIngress=self._sg_rules)
            self.template.add_resource(elb_sg)
            self.template.add_output(
                Output("ElbSecurityGroupOutput",
                       Description="Security group ID assigned to the ELB",
                       Value=Ref(elb_sg),
                       Export=Export(Sub("${AWS::StackName}-ElbSg"))))

            # Build Attachment Security Group
            inst_sg = SecurityGroup(
                "InstanceSecurityGroup",
                GroupDescription=Sub("${AWS::StackName}-InstSg"),
                Tags=self.tags_with(Name=Sub("${AWS::StackName}-InstSg")),
                VpcId=self.vpc_id,
                SecurityGroupEgress=[
                    SecurityGroupRule(CidrIp="0.0.0.0/0", IpProtocol="-1")
                ],
                SecurityGroupIngress=[
                    SecurityGroupRule(IpProtocol="-1",
                                      SourceSecurityGroupId=Ref(elb_sg))
                ])
            self.template.add_resource(inst_sg)
            self.template.add_output(
                Output("InstanceSecurityGroupOutput",
                       Description="Convenience SG to assign to instances",
                       Value=Ref(inst_sg),
                       Export=Export(Sub("${AWS::StackName}-InstSg"))))
            elb_sgs = [Ref("ElbSecurityGroup")]

        # Build ELB
        elb = LoadBalancer("ELB",
                           Name=Ref("AWS::StackName"),
                           SecurityGroups=elb_sgs,
                           Subnets=self.subnet_ids,
                           Tags=self.tags_with(Name=Ref("AWS::StackName")),
                           LoadBalancerAttributes=self.elb_attributes())
        self.template.add_resource(elb)
        self.template.add_output(
            Output("ElbArnOutput",
                   Description="ARN of the ELB",
                   Value=Ref(elb),
                   Export=Export(Sub("${AWS::StackName}-ElbArn"))))
        self.template.add_output(
            Output("ElbDnsOutput",
                   Description="DNS name of the ELB",
                   Value=GetAtt("ELB", "DNSName"),
                   Export=Export(Sub("${AWS::StackName}-ElbDns"))))

        # Build Default Target Group
        if self._ecs_redirect:
            default_tg_protocol = "HTTP"
        else:
            default_tg_protocol = self.default_targets[0].protocol
        default_tg = TargetGroup(
            "DefaultTargetGroup",
            Port=8080,
            Protocol=default_tg_protocol,
            Tags=self.tags_with(Name=Sub("${AWS::StackName}-Default")),
            VpcId=self.vpc_id,
            Targets=list(
                map(lambda h: TargetDescription(Id=h.host, Port=h.port),
                    self.default_targets)),
            HealthyThresholdCount=2,
            Matcher=Matcher(HttpCode="200-399"))
        self.template.add_resource(default_tg)
        self.attach_alarm(default_tg)

        # Build Listener
        self.template.add_resource(
            Listener("HttpsListener",
                     Certificates=list(
                         map(lambda i: Certificate(CertificateArn=i),
                             self.cert_ids)),
                     DefaultActions=[
                         Action(Type="forward",
                                TargetGroupArn=Ref("DefaultTargetGroup"))
                     ],
                     LoadBalancerArn=Ref("ELB"),
                     Port=443,
                     Protocol="HTTPS"))

        # Build HTTP redirect
        if len(self.http_redirect_targets) > 0:
            # Build Redirect Target Group
            http_tg = TargetGroup(
                "RedirectTargetGroup",
                Port=8080,
                Protocol=self.http_redirect_targets[0].protocol,
                Tags=self.tags_with(Name=Sub("${AWS::StackName}-Redirect")),
                VpcId=self.vpc_id,
                Targets=list(
                    map(lambda h: TargetDescription(Id=h.host, Port=h.port),
                        self.http_redirect_targets)),
                HealthyThresholdCount=2,
                Matcher=Matcher(HttpCode="200-399"))
            self.template.add_resource(http_tg)
            self.attach_alarm(http_tg)

        if self._ecs_redirect or len(self.http_redirect_targets) > 0:
            if self._ecs_redirect:
                redirect_tg = "DefaultTargetGroup"
            else:
                redirect_tg = "RedirectTargetGroup"
            # Build Listener
            self.template.add_resource(
                Listener("HttpListener",
                         DefaultActions=[
                             Action(Type="forward",
                                    TargetGroupArn=Ref(redirect_tg))
                         ],
                         LoadBalancerArn=Ref("ELB"),
                         Port=80,
                         Protocol="HTTP"))

        # Build Target Groups & Rules
        for (name, tp) in self.target_paths.iteritems():
            name_an = alpha_numeric_name(name)
            tag_name = taggable_name(name)

            g = TargetGroup(
                "PathTg" + name_an,
                Port=tp.hosts[0].port,
                Protocol=tp.hosts[0].protocol,
                Tags=self.tags_with(Name="%s/%s" % (self.env_name, tag_name),
                                    TargetPath=tag_name),
                Targets=list(map(lambda h: h.to_target_desc(), tp.hosts)),
                VpcId=self.vpc_id,
                HealthCheckPath="/%s" % name,
                HealthyThresholdCount=2,
                Matcher=tp.health_check_matcher)

            # TODO: We should probably explicitly specify this for every TG. Not
            #       doing that now because it will cause lots of updates. Maybe
            #       in 0.4?
            if len(tp.hosts) > 0 and tp.hosts[0].type != "instance":
                g.TargetType = tp.hosts[0].type

            if self.sticky:
                g.TargetGroupAttributes = [
                    TargetGroupAttribute(Key="stickiness.enabled",
                                         Value="true"),
                    TargetGroupAttribute(Key="stickiness.type",
                                         Value="lb_cookie")
                ]
            self.template.add_resource(g)
            self.attach_alarm(g)
            self.template.add_resource(
                ListenerRule(
                    "PathRl" + name_an,
                    Actions=[Action(Type="forward", TargetGroupArn=Ref(g))],
                    Conditions=[
                        Condition(Field="path-pattern",
                                  Values=["/%s/*" % name])
                    ],
                    ListenerArn=Ref("HttpsListener"),
                    Priority=self.priority_hash(name)))
            self.template.add_resource(
                ListenerRule(
                    "PathRln" + name_an,
                    Actions=[Action(Type="forward", TargetGroupArn=Ref(g))],
                    Conditions=[
                        Condition(Field="path-pattern", Values=["/%s" % name])
                    ],
                    ListenerArn=Ref("HttpsListener"),
                    Priority=self.priority_hash(name)))

        # Build Alternate Listeners
        for al in self.alt_listeners:
            tg_name = "AltTg%d" % al.port
            tg_protocol = al.hosts[0].protocol
            tg = TargetGroup(
                tg_name,
                Port=9999,
                Protocol=tg_protocol,
                Tags=self.tags_with(Name=Sub("${AWS::StackName}-%s" %
                                             tg_name)),
                VpcId=self.vpc_id,
                Targets=list(
                    map(lambda h: TargetDescription(Id=h.host, Port=h.port),
                        al.hosts)),
                HealthyThresholdCount=2,
                Matcher=Matcher(HttpCode="200-399"))
            self.template.add_resource(tg)
            self.attach_alarm(tg)

            listener = Listener("AltListener%d" % al.port,
                                DefaultActions=[
                                    Action(Type="forward",
                                           TargetGroupArn=Ref(tg_name))
                                ],
                                LoadBalancerArn=Ref("ELB"),
                                Port=al.port,
                                Protocol=al.protocol)

            if al.protocol == "HTTPS":
                listener.Certificates = list(
                    map(lambda i: Certificate(CertificateArn=i),
                        self.cert_ids))

            self.template.add_resource(listener)

        self._json = self.template.to_json()
        return self._json
Exemplo n.º 6
0
    def add_resources(self):

        self.KongPublicLoadBalancerSecurityGroup = self.template.add_resource(
            ec2.SecurityGroup(
                "KongPublicLoadBalancerSecurityGroup",
                GroupDescription=
                "Enable HTTP access on port 8000m and 8001 for Admin",
                VpcId=Ref(self.VpcId),
                SecurityGroupIngress=[
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8000,
                        ToPort=8001,
                        CidrIp=Ref(self.KongAdminAccess),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8443,
                        ToPort=8444,
                        CidrIp=Ref(self.KongProxyAccess),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=22,
                        ToPort=22,
                        CidrIp=Ref(self.KongAdminAccess),
                    )
                ],
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-KongPublicLBSG"),
            ))

        self.KongPrivateLoadBalancerSecurityGroup = self.template.add_resource(
            ec2.SecurityGroup(
                "KongPrivateLoadBalancerSecurityGroup",
                GroupDescription="Enable HTTP access on port 8000 and 8001",
                VpcId=Ref(self.VpcId),
                SecurityGroupIngress=[
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8000,
                        ToPort=8001,
                        CidrIp=Ref(self.KongAdminAccess),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8443,
                        ToPort=8444,
                        CidrIp=Ref(self.KongProxyAccess),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=22,
                        ToPort=22,
                        CidrIp=Ref(self.KongAdminAccess),
                    )
                ],
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-KongPrivateLBSG"),
            ))

        self.KongPublicLoadBalancer = self.template.add_resource(
            elb.LoadBalancer(
                "KongPublicLoadBalancer",
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPubLB",
                Scheme="internet-facing",
                Subnets=[Ref(self.RESTPubSubnet1),
                         Ref(self.RESTPubSubnet2)],
                SecurityGroups=[Ref(self.KongPublicLoadBalancerSecurityGroup)],
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-KongPubLB"),
            ))

        self.KongPublicSecureProxyTargetGroup = self.template.add_resource(
            elb.TargetGroup(
                "KongPublicSecureProxyTargetGroup",
                HealthCheckIntervalSeconds="30",
                HealthCheckProtocol="HTTP",
                HealthCheckTimeoutSeconds="10",
                HealthyThresholdCount="4",
                Matcher=elb.Matcher(HttpCode="200"),
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPubSecProxyTG",
                Port="8443",
                Protocol="HTTPS",
                UnhealthyThresholdCount="3",
                VpcId=Ref(self.VpcId),
            ))

        self.KongPublicSecureAdminTargetGroup = self.template.add_resource(
            elb.TargetGroup(
                "KongPublicSecureAdminTargetGroup",
                HealthCheckIntervalSeconds="30",
                HealthCheckProtocol="HTTPS",
                HealthCheckTimeoutSeconds="10",
                HealthyThresholdCount="4",
                Matcher=elb.Matcher(HttpCode="200"),
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPubSecAdminTG",
                Port="8444",
                Protocol="HTTPS",
                UnhealthyThresholdCount="3",
                VpcId=Ref(self.VpcId),
            ))

        self.KongPrivateSecureProxyTargetGroup = self.template.add_resource(
            elb.TargetGroup(
                "KongPrivateSecureProxyTargetGroup",
                HealthCheckIntervalSeconds="30",
                HealthCheckProtocol="HTTPS",
                HealthCheckTimeoutSeconds="10",
                HealthyThresholdCount="4",
                Matcher=elb.Matcher(HttpCode="200"),
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPrivateSecProxyTG",
                Port="8443",
                Protocol="HTTPS",
                UnhealthyThresholdCount="3",
                VpcId=Ref(self.VpcId),
            ))

        self.KongPrivateSecureAdminTargetGroup = self.template.add_resource(
            elb.TargetGroup(
                "KongPrivateSecureAdminTargetGroup",
                HealthCheckIntervalSeconds="30",
                HealthCheckProtocol="HTTPS",
                HealthCheckTimeoutSeconds="10",
                HealthyThresholdCount="4",
                Matcher=elb.Matcher(HttpCode="200"),
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPrivSecAdminTG",
                Port="8444",
                Protocol="HTTPS",
                UnhealthyThresholdCount="3",
                VpcId=Ref(self.VpcId),
            ))

        self.KongPublicNonSecureAdminTargetGroup = self.template.add_resource(
            elb.TargetGroup(
                "KongPublicNonSecureAdminTargetGroup",
                HealthCheckIntervalSeconds="30",
                HealthCheckProtocol="HTTP",
                HealthCheckTimeoutSeconds="10",
                HealthyThresholdCount="4",
                Matcher=elb.Matcher(HttpCode="200"),
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPubNonSecAdminTG",
                Port="8001",
                Protocol="HTTP",
                UnhealthyThresholdCount="3",
                VpcId=Ref(self.VpcId),
            ))

        self.KongPrivateLoadBalancer = self.template.add_resource(
            elb.LoadBalancer(
                "KongPrivateLoadBalancer",
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongPrivLB",
                Scheme="internal",
                Subnets=[Ref(self.RESTPrivSubnet1),
                         Ref(self.RESTPrivSubnet2)],
                SecurityGroups=[
                    Ref(self.KongPrivateLoadBalancerSecurityGroup)
                ],
                Tags=Tags(
                    Name=self.environment_parameters["ClientEnvironmentKey"] +
                    "-KongPrivLB") + self.base_tags,
            ))

        self.KongPublicSecureProxyListener = self.template.add_resource(
            elb.Listener(
                "KongPublicSecureProxyListener",
                Port="8443",
                Protocol="HTTPS",
                SslPolicy="ELBSecurityPolicy-2016-08",
                LoadBalancerArn=Ref(self.KongPublicLoadBalancer),
                Certificates=[
                    Certificate(CertificateArn=Ref(self.KongSSLCertificate))
                ],
                DefaultActions=[
                    elb.Action(Type="forward",
                               TargetGroupArn=Ref(
                                   self.KongPublicSecureProxyTargetGroup))
                ]))

        self.KongPublicSecureAdminListener = self.template.add_resource(
            elb.Listener(
                "KongPublicSecureAdminListener",
                Port="8444",
                Protocol="HTTPS",
                SslPolicy="ELBSecurityPolicy-2016-08",
                LoadBalancerArn=Ref(self.KongPublicLoadBalancer),
                Certificates=[
                    Certificate(CertificateArn=Ref(self.KongSSLCertificate))
                ],
                DefaultActions=[
                    elb.Action(Type="forward",
                               TargetGroupArn=Ref(
                                   self.KongPublicSecureAdminTargetGroup))
                ]))

        self.KongPrivateSecureProxyListener = self.template.add_resource(
            elb.Listener(
                "KongPrivateSecureProxyListener",
                Port="8443",
                Protocol="HTTPS",
                SslPolicy="ELBSecurityPolicy-2016-08",
                LoadBalancerArn=Ref(self.KongPrivateLoadBalancer),
                Certificates=[
                    Certificate(CertificateArn=Ref(self.KongSSLCertificate))
                ],
                DefaultActions=[
                    elb.Action(Type="forward",
                               TargetGroupArn=Ref(
                                   self.KongPrivateSecureProxyTargetGroup))
                ]))

        self.KongPrivateSecureAdminListener = self.template.add_resource(
            elb.Listener(
                "KongPrivateSecureAdminListener",
                Port="8444",
                Protocol="HTTPS",
                SslPolicy="ELBSecurityPolicy-2016-08",
                LoadBalancerArn=Ref(self.KongPrivateLoadBalancer),
                Certificates=[
                    Certificate(CertificateArn=Ref(self.KongSSLCertificate))
                ],
                DefaultActions=[
                    elb.Action(Type="forward",
                               TargetGroupArn=Ref(
                                   self.KongPrivateSecureAdminTargetGroup))
                ]))

        self.KongPublicNonSecureAdminListener = self.template.add_resource(
            elb.Listener("KongPublicNonSecureAdminListener",
                         Port="8001",
                         Protocol="HTTP",
                         LoadBalancerArn=Ref(self.KongPublicLoadBalancer),
                         DefaultActions=[
                             elb.Action(
                                 Type="forward",
                                 TargetGroupArn=Ref(
                                     self.KongPublicNonSecureAdminTargetGroup))
                         ]))

        self.KongEC2SecurityGroup = self.template.add_resource(
            ec2.SecurityGroup(
                "KongEC2SecurityGroup",
                GroupDescription=
                "Enable SSH access and HTTP access on the inbound Port",
                VpcId=Ref(self.VpcId),
                SecurityGroupIngress=[
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8000,
                        ToPort=8001,
                        SourceSecurityGroupId=Ref(
                            self.KongPublicLoadBalancerSecurityGroup),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8443,
                        ToPort=8444,
                        SourceSecurityGroupId=Ref(
                            self.KongPublicLoadBalancerSecurityGroup),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8000,
                        ToPort=8001,
                        SourceSecurityGroupId=Ref(
                            self.KongPrivateLoadBalancerSecurityGroup),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8443,
                        ToPort=8444,
                        SourceSecurityGroupId=Ref(
                            self.KongPrivateLoadBalancerSecurityGroup),
                    ),
                    ec2.SecurityGroupRule(
                        IpProtocol="tcp",
                        FromPort=8443,
                        ToPort=8444,
                        SourceSecurityGroupId=Ref(
                            self.KongPrivateLoadBalancerSecurityGroup),
                    )
                ],
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-KongEc2SG"),
            ))

        self.CassandraSGKongCommunicationIngress = self.template.add_resource(
            ec2.SecurityGroupIngress(
                "CassandraSGKongCommunicationIngress",
                DependsOn=self.KongEC2SecurityGroup,
                GroupId=Ref(self.CassandraSG),
                IpProtocol="tcp",
                FromPort=Ref(self.CassandraPort),
                ToPort=Ref(self.CassandraPort),
                SourceSecurityGroupId=Ref(self.KongEC2SecurityGroup),
            ))

        self.ASGUpdateRole = self.template.add_resource(
            Role("ASGUpdateRole",
                 AssumeRolePolicyDocument=Policy(Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   ["ec2.amazonaws.com"]))
                 ]),
                 Policies=[
                     iam.Policy(
                         PolicyName="ASGUpdateRole",
                         PolicyDocument={
                             "Version":
                             "2012-10-17",
                             "Statement": [{
                                 "Action": [
                                     "ec2:Describe*",
                                     "cloudformation:DescribeStackResource"
                                 ],
                                 "Effect":
                                 "Allow",
                                 "Resource":
                                 "*"
                             }]
                         })
                 ]))

        self.ASGUpdateProfile = self.template.add_resource(
            InstanceProfile(
                "ASGUpdateProfile",
                Path="/",
                Roles=[Ref(self.ASGUpdateRole)],
            ))

        self.KongVersionSSMParameter = self.template.add_resource(
            SSMParameter(
                "KongVersionSSMParameter",
                Description="The Kong Version",
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongVersion",
                Type="String",
                Value=Ref(self.KongVersionSSMParameterValue),
            ))

        self.KongExecuteMigrationsSSMParameter = self.template.add_resource(
            SSMParameter(
                "KongExecuteMigrationsSSMParameter",
                Description=
                "Flag to determine if Kong should Execute DB migrations",
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-KongExecuteMigrations",
                Type="String",
                Value=Ref(self.KongExecuteMigrationsSSMParameterValue),
            ))

        self.CassandraSeedListSSMParameter = self.template.add_resource(
            SSMParameter(
                "CassandraSeedListSSMParameter",
                Description="The Cassandra Seed Node List",
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-CassandraSeedList",
                Type="String",
                Value=Ref(self.CassandraSeedListSSMParameterValue),
            ))

        self.KongLaunchConfig = self.template.add_resource(
            LaunchConfiguration(
                "KongLaunchConfig",
                ImageId="ami-a4c7edb2",
                AssociatePublicIpAddress="false",
                InstanceType=Ref(self.KongInstanceType),
                IamInstanceProfile=Ref(self.KongIAMInstanceProfile),
                KeyName=Ref(self.KongKeyName),
                SecurityGroups=[Ref(self.KongEC2SecurityGroup)],
                UserData=Base64(
                    Join('', [
                        "#!/bin/bash\n",
                        "yum update -y \n",
                        "pip install --upgrade pip \n",
                        "pip install --upgrade awscli \n",
                        "ClientCode=\"" +
                        self.environment_parameters["ClientEnvironmentKey"] +
                        "\" \n",
                        "REGION=\"" +
                        self.environment_parameters["EnvironmentRegion"] +
                        "\" \n",
                        "BootstrapRepositorySSMKey=\"-bootstrapRepository\" \n",
                        "BootstrapRepositorySSMKey=${ClientCode}${BootstrapRepositorySSMKey} \n",
                        "echo $BootstrapRepositorySSMKey \n",
                        "bootstrapRepository=\"$(aws ssm get-parameter --name ${BootstrapRepositorySSMKey} --region ${REGION} --output text --query 'Parameter.Value')\" \n",
                        "echo $bootstrapRepository \n",
                        "keyprefix=\"/bootstrap/rest/bash\" \n",
                        "localpath=\"/tmp/bootstrap\" \n",
                        "echo $bootStrapRepository \n",
                        "if [ ! -d \"${localpath}\"]; then \n",
                        "mkdir - p \n",
                        "\"${localpath}\" \n",
                        "fi \n",
                        "FullS3Path=${bootstrapRepository}${keyprefix} \n",
                        "echo $FullS3Path \n",
                        "aws s3 sync s3://$FullS3Path $localpath \n",
                        "chmod u+x /tmp/bootstrap/kong-provision.sh \n",
                        "/bin/bash /tmp/bootstrap/kong-provision.sh \n",
                    ]))))

        self.KongScalingGroup = self.template.add_resource(
            AutoScalingGroup(
                "KongScalingGroup",
                AutoScalingGroupName=self.
                environment_parameters["ClientEnvironmentKey"] +
                "-KongAutoScalingGroup",
                AvailabilityZones=["us-east-1a"],
                LaunchConfigurationName=Ref(self.KongLaunchConfig),
                VPCZoneIdentifier=[Ref(self.RESTPrivSubnet1)],
                MinSize="1",
                MaxSize="1",
                DesiredCapacity="1",
                TargetGroupARNs=[
                    Ref(self.KongPublicNonSecureAdminTargetGroup),
                    Ref(self.KongPrivateSecureAdminTargetGroup),
                    Ref(self.KongPrivateSecureProxyTargetGroup),
                    Ref(self.KongPublicSecureAdminTargetGroup),
                    Ref(self.KongPublicSecureProxyTargetGroup)
                ],
                Tags=[
                    AutoScalingTag(
                        "Name",
                        self.environment_parameters["ClientEnvironmentKey"] +
                        "-Kong-Ec2", True),
                    AutoScalingTag(
                        "Environment",
                        self.environment_parameters["EnvironmentName"], True),
                    AutoScalingTag(
                        "ResourceOwner",
                        self.environment_parameters["ResourceOwner"], True),
                    AutoScalingTag(
                        "ClientCode",
                        self.environment_parameters["ClientEnvironmentKey"],
                        True),
                ],
            ))
Exemplo n.º 7
0
def create_alb_template():
    template = Template()

    vpc = template.add_parameter(
        parameter=Parameter(title='Vpc', Type='String'))
    subnet_a = template.add_parameter(
        parameter=Parameter(title='SubnetA', Type='String'))
    subnet_b = template.add_parameter(
        parameter=Parameter(title='SubnetB', Type='String'))
    ec2_instance = template.add_parameter(
        parameter=Parameter(title='Ec2Instance', Type='String'))
    certificate = template.add_parameter(
        parameter=Parameter(title='Certificate', Type='String'))

    security_group = template.add_resource(
        resource=SecurityGroup(title='SampleSecurityGroup',
                               GroupDescription='sample-security-group',
                               SecurityGroupIngress=[{
                                   'IpProtocol': 'tcp',
                                   'FromPort': 80,
                                   'ToPort': 80,
                                   'CidrIp': '0.0.0.0/0'
                               }, {
                                   'IpProtocol': 'tcp',
                                   'FromPort': 443,
                                   'ToPort': 443,
                                   'CidrIp': '0.0.0.0/0'
                               }],
                               VpcId=Ref(vpc)))

    load_balancer = template.add_resource(resource=LoadBalancer(
        title='SampleLoadBalancer',
        Name='sample-alb-https',
        Subnets=[Ref(subnet_a), Ref(subnet_b)],
        SecurityGroups=[Ref(security_group)],
    ))

    target_group = template.add_resource(resource=TargetGroup(
        title='SampleTargetGroup',
        Targets=[TargetDescription(
            Id=Ref(ec2_instance),
            Port=80,
        )],
        VpcId=Ref(vpc),
        Name='sample-target-group-https',
        Port=443,
        Protocol='HTTP',
    ))

    template.add_resource(resource=Listener(
        title='SampleListenerHttps',
        Certificates=[Certificate(CertificateArn=Ref(certificate))],
        DefaultActions=[
            Action(TargetGroupArn=Ref(target_group), Type='forward')
        ],
        LoadBalancerArn=Ref(load_balancer),
        Port=443,
        Protocol='HTTPS',
    ))

    template.add_resource(resource=Listener(
        title='SampleListenerHttp',
        DefaultActions=[
            Action(
                RedirectConfig=RedirectConfig(
                    Host='#{host}',
                    Path='/#{path}',
                    Port='443',
                    Protocol='HTTPS',
                    Query='#{query}',
                    StatusCode='HTTP_301',
                ),
                Type='redirect',
            )
        ],
        LoadBalancerArn=Ref(load_balancer),
        Port=80,
        Protocol='HTTP',
    ))

    with open('./alb.yml', mode='w') as file:
        file.write(template.to_yaml())
Exemplo n.º 8
0
        LoadBalancerAttributes(Key="access_logs.s3.prefix", Value="alb")
    ],
    SecurityGroups=[Ref(alb_security_group)],
    DependsOn=Ref(logs_bucket_policy))
template.add_resource(load_balancer)
target_group = TargetGroup("exampletargetgroup",
                           VpcId=vpc_id,
                           HealthCheckPath='/',
                           Port='80',
                           Protocol='HTTP')
listener = Listener(
    "examplelistener",
    LoadBalancerArn=Ref(load_balancer),
    Port='443',
    Protocol='HTTPS',
    Certificates=[Certificate(CertificateArn=certificate_arn)],
    DefaultActions=[Action(Type='forward', TargetGroupArn=Ref(target_group))],
    SslPolicy="ELBSecurityPolicy-TLS-1-2-Ext-2018-06")
template.add_resource(target_group)
template.add_resource(listener)

# Setup the ASG & launch config
launch_config = LaunchConfiguration(
    "LaunchConfig",
    ImageId=image_id,
    IamInstanceProfile=Ref(example_instance_profile),
    InstanceType=instance_type,
    Metadata=Metadata(
        Init({
            'config':
            InitConfig(
Exemplo n.º 9
0
                Protocol = "HTTPS",
                StatusCode = "HTTP_301"
            ),
            Type = "redirect"
        )
    ],
    LoadBalancerArn = Ref(application_load_balancer),
    Port = 80,
    Protocol = "HTTP"
)

https_listener = Listener(
    region.replace("-", "") + "ecslivehttpslistener",
    Certificates = [
        Certificate(
            CertificateArn = Ref(origin_issued_certificate)
        )
    ],
    DefaultActions = [
        Action(
            region.replace("-", "") + "ecslivehttpsfixedresponseaction",
            FixedResponseConfig = FixedResponseConfig(
                region.replace("-", "") + "ecslivehttpredirectconfig",
                ContentType = "text/plain",
                MessageBody = "Service Unavailable",
                StatusCode = "503"
            ),
            Order = 50000,
            Type = "fixed-response"
        )
Exemplo n.º 10
0
    Subnets=[
        Ref(loadbalancer_a_subnet),
        Ref(loadbalancer_b_subnet),
    ],
    SecurityGroups=[Ref(load_balancer_security_group)],
)

template.add_output(
    Output("LoadBalancerDNSName",
           Description="Loadbalancer DNS",
           Value=GetAtt(application_load_balancer, "DNSName")))

application_listener = Listener(
    'ApplicationListener',
    template=template,
    Certificates=[Certificate(CertificateArn=application_certificate, )],
    LoadBalancerArn=Ref(application_load_balancer),
    Protocol='HTTPS',
    Port=443,
    DefaultActions=[
        Action(
            TargetGroupArn=Ref(application_target_group),
            Type='forward',
        )
    ])

# ECS cluster
cluster = Cluster(
    "Cluster",
    template=template,
)
Exemplo n.º 11
0
                               Path="/#{path}",
                               Port="443",
                               Protocol="HTTPS",
                               Query="#{query}",
                               StatusCode="HTTP_301"))
                ],
                LoadBalancerArn=Ref(resources["ALB"]),
                Port=80,
                Protocol="HTTP"))

resources["ALBHTTPSlistener"] = template.add_resource(
    AppListener("ALBHTTPSlistener",
                DependsOn=[resource for resource in ["ALB", "ALBTargetGroup"]],
                Certificates=[
                    Certificate("ALBCertificate",
                                CertificateArn=Ref(
                                    parameters["SSLCertificateALB"]))
                ],
                DefaultActions=[
                    Action(Type='forward',
                           TargetGroupArn=Ref("ALBTargetGroup"))
                ],
                LoadBalancerArn=Ref(resources["ALB"]),
                Port=443,
                Protocol="HTTPS"))

### Application Load Balancer Target Group ###

resources["ALBTargetGroup"] = template.add_resource(
    TargetGroup(
        "ALBTargetGroup",