예제 #1
0
 def elb_attributes(self):
     ret = [
         LoadBalancerAttributes(Key="idle_timeout.timeout_seconds",
                                Value=str(self.idle_timeout_seconds))
     ]
     if self._log_bucket is not None:
         ret += [
             LoadBalancerAttributes(Key="access_logs.s3.enabled",
                                    Value="true"),
             LoadBalancerAttributes(Key="access_logs.s3.bucket",
                                    Value=self._log_bucket),
             LoadBalancerAttributes(Key="access_logs.s3.prefix",
                                    Value=Sub("${AWS::StackName}-ElbLogs"))
         ]
     return ret
예제 #2
0
def handle_drop_invalid_headers(value) -> LoadBalancerAttributes:
    """
    Handles MacroParamters for drop invalid headers.
    """
    return LoadBalancerAttributes(
        Key="routing.http.drop_invalid_header_fields.enabled",
        Value=str(value).lower(),
    )
예제 #3
0
def handle_desync_mitigation_mode(value) -> LoadBalancerAttributes:
    """
    Handles MacroParamters for desync mitigation.
    """
    if value not in ["defensive", "strictest", "monitor"]:
        raise ValueError(
            "desync_mitigation_mode must be one of",
            ["defensive", "strictest", "monitor"],
        )
    return LoadBalancerAttributes(Key="routing.http.desync_mitigation_mode",
                                  Value=str(value).lower())
예제 #4
0
def handle_timeout_seconds(timeout_seconds) -> LoadBalancerAttributes:
    """
    Handles MacroParamters for timeout.
    """
    if 1 < int(timeout_seconds) < 4000:
        return LoadBalancerAttributes(
            Key="idle_timeout.timeout_seconds",
            Value=str(timeout_seconds).lower(),
        )
    else:
        raise ValueError(
            "idle_timeout.timeout_seconds must be set between 1 and 4000 seconds. Got",
            timeout_seconds,
        )
예제 #5
0
 def add_load_balancer(self):
     '''
     Add load balancer to template
     '''
     self.cfn_template.add_resource(LoadBalancer(
         title=constants.ALB,
         LoadBalancerAttributes=[LoadBalancerAttributes(
             Key='deletion_protection.enabled',
             Value='false'
         )],
         Scheme='internal',
         SecurityGroups=[Ref(constants.ALB_SG)],
         Subnets=[
             ImportValue(Sub('${Environment}-${Subnet1}')),
             ImportValue(Sub('${Environment}-${Subnet2}'))
         ]
     ))
     return self.cfn_template
예제 #6
0
    def set_lb_attributes(self):
        """
        Method to define the LB attributes

        :return: List of LB Attributes
        :rtype: list
        """
        attributes = []
        if keyisset("LoadBalancerAttributes", self.properties):
            for prop in self.properties["LoadBalancerAttributes"]:
                attributes.append(
                    LoadBalancerAttributes(
                        Key=prop,
                        Value=self.properties["LoadBalancerAttributes"][prop],
                    ))
        elif (not keyisset("LoadBalancerAttributes", self.definition)
              and self.parameters):
            attributes = self.parse_attributes_settings()
        if attributes:
            return attributes
        return Ref(AWS_NO_VALUE)
예제 #7
0
    def parse_attributes_settings(self):
        """
        Method to parse pre-defined settings for shortcuts

        :return: the lb attributes mappings
        :rtype: list
        """
        valid_settings = [
            ("timeout_seconds", int, handle_timeout_seconds, self.is_alb()),
            (
                "desync_mitigation_mode",
                str,
                handle_desync_mitigation_mode,
                self.is_alb(),
            ),
            (
                "drop_invalid_header_fields",
                bool,
                handle_drop_invalid_headers,
                self.is_alb(),
            ),
            ("http2", bool, handle_http2, self.is_alb()),
            ("cross_zone", bool, handle_cross_zone, self.is_nlb()),
        ]
        mappings = []
        for setting in valid_settings:
            if (keypresent(setting[0], self.parameters)
                    and isinstance(self.parameters[setting[0]], setting[1])
                    and setting[3]):
                if setting[2] and setting[3]:
                    mappings.append(setting[2](self.parameters[setting[0]]))
                elif setting[3]:
                    mappings.append(
                        LoadBalancerAttributes(
                            Key=setting[0],
                            Value=str(self.parameters[setting[0]]),
                        ))
        return mappings
예제 #8
0
                          ToPort="8080",
                          SourceSecurityGroupId=Ref(api_elb_sg),
                      ),
                      SecurityGroupRule(
                          IpProtocol="tcp",
                          FromPort="22",
                          ToPort="22",
                          CidrIp='0.0.0.0/0',
                      )
                  ]))

load_balancer = template.add_resource(
    LoadBalancer('ApplicationElasticLB',
                 Name=Join('-', ['api', 'elb', Ref(version)]),
                 LoadBalancerAttributes=[
                     LoadBalancerAttributes(Key='access_logs.s3.enabled',
                                            Value='false'),
                     LoadBalancerAttributes(Key='idle_timeout.timeout_seconds',
                                            Value='60'),
                 ],
                 Scheme='internet-facing',
                 SecurityGroups=[Ref(api_elb_sg)],
                 Subnets=Ref(subnets)))

target_group = template.add_resource(
    TargetGroup(
        'DefaultTargetGroup',
        Name=Join('-', ['api', 'default', Ref(version)]),
        HealthCheckIntervalSeconds=5,
        HealthCheckProtocol='HTTP',
        HealthCheckTimeoutSeconds=2,
        HealthCheckPath='/',
예제 #9
0
def handle_http2(value: str) -> LoadBalancerAttributes:
    """
    Handles MacroParamters for HTTP2.
    """
    return LoadBalancerAttributes(Key="routing.http2.enabled",
                                  Value=str(value).lower())
예제 #10
0
def handle_cross_zone(value: str) -> LoadBalancerAttributes:
    """
    Handles MacroParamters for cross-zone.
    """
    return LoadBalancerAttributes(Key="load_balancing.cross_zone.enabled",
                                  Value=str(value).lower())
예제 #11
0
            "Resource":
            Join("", ['s3:::', Ref(logs_bucket), "/alb/*"]),
            "Principal": {
                "AWS": Ref("AWS::AccountId")
            }
        }]
    })
template.add_resource(logs_bucket)
template.add_resource(logs_bucket_policy)

# Create Application Load Balancer
load_balancer = LoadBalancer(
    "exampleloadbalancer",
    Subnets=subnet_ids,
    LoadBalancerAttributes=[
        LoadBalancerAttributes(Key="access_logs.s3.enabled", Value="true"),
        LoadBalancerAttributes(Key="access_logs.s3.bucket", Value="true"),
        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',
예제 #12
0
    VPCZoneIdentifier = [
        "subnet-0777c674d3018efd6",
        "subnet-0dec29b6660100d8d",
        "subnet-095d86cbe447af65e"
    ]
)

template.add_resource(auto_scaling_group)

# TODO: sort out ipv6 on vpc so can use dualstack here
application_load_balancer = LoadBalancer(
    region.replace("-", "") + "ecsliveapplicationloadbalancer",
    IpAddressType = "ipv4",
    LoadBalancerAttributes = [
        LoadBalancerAttributes(
            Key="access_logs.s3.enabled",
            Value = "true"
        ),
        LoadBalancerAttributes(
            Key="access_logs.s3.bucket",
            Value = "mgmt.eu-west-1.weblox.io"
        ),
        LoadBalancerAttributes(
            Key="access_logs.s3.prefix",
            Value = "logs"
        )
    ],
    Scheme = "internet-facing",
    SecurityGroups = [
        Ref(alb_security_group),
        Ref(security_group)
    ],
예제 #13
0
    def add_load_balancer(self, settings):
        """
        Method to add LB to template

        :return: loadbalancer
        :rtype: troposphere.elasticloadbalancingv2.LoadBalancer
        """
        if self.config.is_public and self.config.use_nlb():
            self.add_public_ips(settings.aws_azs)

        no_value = Ref(AWS_NO_VALUE)
        public_mapping = define_public_mapping(self.eips, settings.aws_azs)
        if self.config.ingress_mappings and self.config.use_alb():
            self.add_alb_sg(self.config.ingress_mappings.keys())
            lb_sg = [Ref(self.alb_sg)]
        else:
            lb_sg = no_value

        loadbalancer = LoadBalancer(
            f"Microservice{self.config.lb_type.title()}LB",
            template=self.template,
            Scheme="internet-facing" if self.config.is_public else "internal",
            LoadBalancerAttributes=[
                LoadBalancerAttributes(Key="load_balancing.cross_zone.enabled",
                                       Value="true")
            ] if self.config.lb_type == "network" else no_value,
            SecurityGroups=lb_sg,
            SubnetMappings=public_mapping
            if self.config.is_public and self.config.use_nlb() else no_value,
            Subnets=Ref(PUBLIC_SUBNETS) if self.config.is_public
            and self.config.use_alb() else Ref(vpc_params.APP_SUBNETS),
            Type=self.config.lb_type,
            Tags=Tags({
                "Name":
                Sub(f"${{{SERVICE_NAME_T}}}-${{{ROOT_STACK_NAME_T}}}"),
                "StackName":
                Ref(AWS_STACK_NAME),
                "MicroserviceName":
                Ref(SERVICE_NAME),
            }),
        )
        if self.config.is_public:
            sd_service = SdService(
                f"{self.resource_name}PublicDiscoveryService",
                template=self.template,
                Description=Ref(SERVICE_NAME),
                Condition=CREATE_PUBLIC_NAMESPACE_CON_T,
                NamespaceId=Ref(PUBLIC_DNS_ZONE_ID),
                HealthCheckCustomConfig=SdHealthCheckCustomConfig(
                    FailureThreshold=1.0),
                DnsConfig=SdDnsConfig(
                    RoutingPolicy="WEIGHTED",
                    NamespaceId=Ref(AWS_NO_VALUE),
                    DnsRecords=[SdDnsRecord(TTL="15", Type="A")],
                ),
                Name=If(USE_HOSTNAME_CON_T, Ref(SERVICE_HOSTNAME),
                        Ref(SERVICE_NAME)),
            )
            SdInstance(
                f"{self.resource_name}PublicLB",
                template=self.template,
                Condition=CREATE_PUBLIC_NAMESPACE_CON_T,
                ServiceId=GetAtt(sd_service, "Id"),
                InstanceAttributes={
                    "AWS_ALIAS_DNS_NAME": GetAtt(loadbalancer, "DNSName")
                },
            )
            if self.config.use_alb() and self.alb_sg:
                self.add_public_security_group_ingress(self.alb_sg)
            elif self.config.use_nlb():
                self.add_public_security_group_ingress(SG_T)
        return loadbalancer