Example #1
0
    def __init__(self, title, **kwargs):
        super().__init__(title, **kwargs)

        self.HealthCheckIntervalSeconds = get_endvalue(
            'HealthCheckIntervalSeconds')
        self.HealthCheckTimeoutSeconds = get_endvalue(
            'HealthCheckTimeoutSeconds')
        if cfg.HealthCheckPath != 'None':
            self.HealthCheckPath = get_endvalue('HealthCheckPath')
        self.HealthyThresholdCount = get_endvalue('HealthyThresholdCount')
        self.UnhealthyThresholdCount = get_endvalue('UnhealthyThresholdCount')
        self.TargetGroupAttributes = [
            elbv2.TargetGroupAttribute(
                Key='deregistration_delay.timeout_seconds',
                Value=get_endvalue('TargetGroupDeregistrationDelay')),
            elbv2.TargetGroupAttribute(Key='stickiness.enabled',
                                       Value=If(
                                           'TargetGroupCookieSticky',
                                           'true',
                                           'false',
                                       )),
            If(
                'TargetGroupCookieSticky',
                elbv2.TargetGroupAttribute(
                    Key='stickiness.lb_cookie.duration_seconds',
                    Value=get_endvalue('TargetGroupCookieSticky')),
                Ref('AWS::NoValue'))
        ]
        self.Protocol = get_endvalue('TargetGroupProtocol')
        self.VpcId = get_expvalue('VpcId')
Example #2
0
    def add_alb(self, template, provision_refs, instances):

        alb = template.add_resource(
            elb.LoadBalancer(
                'ALB',
                LoadBalancerAttributes=[
                    elb.LoadBalancerAttributes(
                        Key='idle_timeout.timeout_seconds', Value='3600')
                ],
                Subnets=provision_refs.subnets,
                Type='application',
                Scheme='internet-facing',
                IpAddressType='ipv4',
                SecurityGroups=[provision_refs.security_group_alb]))

        default_target_group = template.add_resource(
            elb.TargetGroup(
                'DefaultTargetGroup',
                Port=46658,
                Protocol='HTTP',
                Targets=[
                    elb.TargetDescription(Id=Ref(instance))
                    for instance in instances
                ],
                HealthCheckProtocol='HTTP',
                HealthCheckPath='/rpc',
                TargetGroupAttributes=[
                    elb.TargetGroupAttribute(Key='stickiness.enabled',
                                             Value='true'),
                    elb.TargetGroupAttribute(Key='stickiness.type',
                                             Value='lb_cookie'),
                    elb.TargetGroupAttribute(
                        Key='stickiness.lb_cookie.duration_seconds',
                        Value='86400'),
                ],
                VpcId=provision_refs.vpc))

        template.add_resource(
            elb.Listener(
                'ALBListener',
                DefaultActions=[
                    elb.Action('DefaultAction',
                               Type='forward',
                               TargetGroupArn=Ref(default_target_group))
                ],
                LoadBalancerArn=Ref(alb),
                Port=46658,
                Protocol='HTTPS',
                SslPolicy='ELBSecurityPolicy-TLS-1-2-2017-01',
                Certificates=[
                    elb.Certificate(
                        CertificateArn=
                        'arn:aws:acm:us-east-1:489745816517:certificate/'
                        'fbb68210-264e-4340-9c5c-a7687f993579')
                ]))

        provision_refs.alb = alb
Example #3
0
def create_target_group(stack,
                        name,
                        port,
                        protocol='HTTPS',
                        targets=[],
                        http_codes='200',
                        health_check_path='/',
                        target_type='instance',
                        attributes=False):
    """Add Target Group Resource."""
    target_objects = []

    for target in targets:
        target_objects.append(alb.TargetDescription(Id=target))

    tg_atts = []

    if not attributes:
        tg_atts.append(
            alb.TargetGroupAttribute(
                Key='deregistration_delay.timeout_seconds', Value='300'))
    else:
        for att, value in attributes.items():
            tg_atts.append(alb.TargetGroupAttribute(Key=att, Value=value))

    if http_codes is not None:
        return stack.stack.add_resource(
            alb.TargetGroup('{0}TargetGroup'.format(name),
                            HealthCheckIntervalSeconds='30',
                            HealthCheckProtocol=protocol,
                            HealthCheckTimeoutSeconds='10',
                            HealthyThresholdCount='4',
                            HealthCheckPath=health_check_path,
                            Matcher=alb.Matcher(HttpCode=http_codes),
                            Name='{0}Target'.format(name),
                            Port=port,
                            Protocol=protocol,
                            Targets=target_objects,
                            TargetType=target_type,
                            UnhealthyThresholdCount='3',
                            TargetGroupAttributes=tg_atts,
                            VpcId=Ref(stack.vpc)))

    return stack.stack.add_resource(
        alb.TargetGroup('{0}TargetGroup'.format(name),
                        HealthCheckIntervalSeconds='30',
                        HealthCheckProtocol=protocol,
                        HealthCheckTimeoutSeconds='10',
                        HealthyThresholdCount='3',
                        Name='{0}Target'.format(name),
                        Port=port,
                        Protocol=protocol,
                        Targets=targets,
                        UnhealthyThresholdCount='3',
                        TargetType=target_type,
                        TargetGroupAttributes=tg_atts,
                        VpcId=Ref(stack.vpc)))
    def configure_alb(self, t, service):
        service_target_group = t.add_resource(elasticloadbalancingv2.TargetGroup(
            self.resource_name_format % ('ServiceTargetGroup'),
            Port=80,
            Protocol="HTTP",
            HealthCheckPath=self.healthcheck_path,
            HealthCheckIntervalSeconds=self.healthcheck_interval,
            HealthCheckTimeoutSeconds=self.healthcheck_interval - 1,
            HealthyThresholdCount=2,
            UnhealthyThresholdCount=5,
            VpcId=ImportValue(Sub(self.imports_format % ('VpcId'))),
            TargetGroupAttributes=[
                elasticloadbalancingv2.TargetGroupAttribute(Key=key, Value=value)
                for (key, value) in sorted(self.target_group_attributes().items())
            ]
        ))

        listener_rule = t.add_resource(elasticloadbalancingv2.ListenerRule(
            self.resource_name_format % ('SecureListenerRule'),
            ListenerArn=ImportValue(Sub(self.imports_format % ('PublicListener' if self.public else 'InternalListener'))),
            Priority=self.priority,
            Actions=[elasticloadbalancingv2.Action(Type="forward", TargetGroupArn=Ref(service_target_group))],
            Conditions=[elasticloadbalancingv2.Condition(Field="host-header", Values=self.domains)]
        ))

        service.DependsOn.append(listener_rule.title)
        service.LoadBalancers = [
            ecs.LoadBalancer(
                ContainerName=self.container_name,
                ContainerPort=self.port,
                TargetGroupArn=Ref(service_target_group)
            )
        ]
Example #5
0
 def gen_target_group(self):
     self.target_group = elasticloadbalancingv2.TargetGroup(
         "TargetGroup",
         VpcId=self.import_value("vpc", "VPC"),
         Port="80",
         TargetGroupAttributes=[
             elasticloadbalancingv2.TargetGroupAttribute(
                 Key="deregistration_delay.timeout_seconds", Value="10"),
         ],
         TargetType="ip",
         Protocol="HTTP",
         HealthCheckPath="/demo",
     )
     self.template.add_resource(self.target_group)
Example #6
0
def buildStack(bootstrap, env):
    t = Template()

    t.add_description("""\
    Configures autoscaling group for hello world app""")

    vpcCidr = t.add_parameter(
        Parameter(
            "VPCCidr",
            Type="String",
            Description="VPC cidr (x.x.x.x/xx)",
        ))

    publicSubnet1 = t.add_parameter(
        Parameter(
            "PublicSubnet1",
            Type="String",
            Description="A public VPC subnet ID for the api app load balancer.",
        ))

    publicSubnet2 = t.add_parameter(
        Parameter(
            "PublicSubnet2",
            Type="String",
            Description="A public VPC subnet ID for the api load balancer.",
        ))

    dbName = t.add_parameter(
        Parameter(
            "DBName",
            Default="HelloWorldApp",
            Description="The database name",
            Type="String",
            MinLength="1",
            MaxLength="64",
            AllowedPattern="[a-zA-Z][a-zA-Z0-9]*",
            ConstraintDescription=("must begin with a letter and contain only"
                                   " alphanumeric characters.")))

    dbUser = t.add_parameter(
        Parameter(
            "DBUser",
            NoEcho=True,
            Description="The database admin account username",
            Type="String",
            MinLength="1",
            MaxLength="16",
            AllowedPattern="[a-zA-Z][a-zA-Z0-9]*",
            ConstraintDescription=("must begin with a letter and contain only"
                                   " alphanumeric characters.")))

    dbPassword = t.add_parameter(
        Parameter(
            "DBPassword",
            NoEcho=True,
            Description="The database admin account password",
            Type="String",
            MinLength="8",
            MaxLength="41",
            AllowedPattern="[a-zA-Z0-9]*",
            ConstraintDescription="must contain only alphanumeric characters.")
    )

    dbType = t.add_parameter(
        Parameter(
            "DBType",
            Default="db.t2.medium",
            Description="Database instance class",
            Type="String",
            AllowedValues=[
                "db.m5.large", "db.m5.xlarge", "db.m5.2xlarge",
                "db.m5.4xlarge", "db.m5.12xlarge", "db.m5.24xlarge",
                "db.m4.large", "db.m4.xlarge", "db.m4.2xlarge",
                "db.m4.4xlarge", "db.m4.10xlarge", "db.m4.16xlarge",
                "db.r4.large", "db.r4.xlarge", "db.r4.2xlarge",
                "db.r4.4xlarge", "db.r4.8xlarge", "db.r4.16xlarge",
                "db.x1e.xlarge", "db.x1e.2xlarge", "db.x1e.4xlarge",
                "db.x1e.8xlarge", "db.x1e.16xlarge", "db.x1e.32xlarge",
                "db.x1.16xlarge", "db.x1.32xlarge", "db.r3.large",
                "db.r3.xlarge", "db.r3.2xlarge", "db.r3.4xlarge",
                "db.r3.8xlarge", "db.t2.micro", "db.t2.small", "db.t2.medium",
                "db.t2.large", "db.t2.xlarge", "db.t2.2xlarge"
            ],
            ConstraintDescription="must select a valid database instance type.",
        ))

    dbAllocatedStorage = t.add_parameter(
        Parameter(
            "DBAllocatedStorage",
            Default="5",
            Description="The size of the database (Gb)",
            Type="Number",
            MinValue="5",
            MaxValue="1024",
            ConstraintDescription="must be between 5 and 1024Gb.",
        ))

    whitelistedCIDR = t.add_parameter(
        Parameter(
            "WhitelistedCIDR",
            Description="CIDR whitelisted to be open on public instances",
            Type="String",
        ))

    #### NETWORK SECTION ####
    vpc = t.add_resource(
        VPC("VPC", CidrBlock=Ref(vpcCidr), EnableDnsHostnames=True))

    subnet1 = t.add_resource(
        Subnet("Subnet1",
               CidrBlock=Ref(publicSubnet1),
               AvailabilityZone="eu-west-1a",
               VpcId=Ref(vpc)))
    subnet2 = t.add_resource(
        Subnet("Subnet2",
               CidrBlock=Ref(publicSubnet2),
               AvailabilityZone="eu-west-1b",
               VpcId=Ref(vpc)))

    internetGateway = t.add_resource(InternetGateway('InternetGateway'))

    gatewayAttachment = t.add_resource(
        VPCGatewayAttachment('AttachGateway',
                             VpcId=Ref(vpc),
                             InternetGatewayId=Ref(internetGateway)))

    routeTable = t.add_resource(RouteTable('RouteTable', VpcId=Ref(vpc)))

    route = t.add_resource(
        Route(
            'Route',
            DependsOn='AttachGateway',
            GatewayId=Ref('InternetGateway'),
            DestinationCidrBlock='0.0.0.0/0',
            RouteTableId=Ref(routeTable),
        ))

    subnetRouteTableAssociation = t.add_resource(
        SubnetRouteTableAssociation(
            'SubnetRouteTableAssociation',
            SubnetId=Ref(subnet1),
            RouteTableId=Ref(routeTable),
        ))

    subnetRouteTableAssociation2 = t.add_resource(
        SubnetRouteTableAssociation(
            'SubnetRouteTableAssociation2',
            SubnetId=Ref(subnet2),
            RouteTableId=Ref(routeTable),
        ))

    #### SECURITY GROUP ####
    loadBalancerSg = t.add_resource(
        ec2.SecurityGroup(
            "LoadBalancerSecurityGroup",
            VpcId=Ref(vpc),
            GroupDescription="Enable SSH access via port 22",
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort="80",
                    ToPort="80",
                    CidrIp="0.0.0.0/0",
                ),
            ],
        ))

    instanceSg = t.add_resource(
        ec2.SecurityGroup(
            "InstanceSecurityGroup",
            VpcId=Ref(vpc),
            GroupDescription="Enable SSH access via port 22",
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort="22",
                    ToPort="22",
                    CidrIp=Ref(whitelistedCIDR),
                ),
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort="8000",
                    ToPort="8000",
                    SourceSecurityGroupId=Ref(loadBalancerSg),
                ),
            ],
        ))

    rdsSg = t.add_resource(
        SecurityGroup("RDSSecurityGroup",
                      GroupDescription="Security group for RDS DB Instance.",
                      VpcId=Ref(vpc),
                      SecurityGroupIngress=[
                          ec2.SecurityGroupRule(
                              IpProtocol="tcp",
                              FromPort="5432",
                              ToPort="5432",
                              SourceSecurityGroupId=Ref(instanceSg),
                          ),
                          ec2.SecurityGroupRule(
                              IpProtocol="tcp",
                              FromPort="5432",
                              ToPort="5432",
                              CidrIp=Ref(whitelistedCIDR),
                          ),
                      ]))

    #### DATABASE SECTION ####
    subnetGroup = t.add_resource(
        DBSubnetGroup(
            "SubnetGroup",
            DBSubnetGroupDescription=
            "Subnets available for the RDS DB Instance",
            SubnetIds=[Ref(subnet1), Ref(subnet2)],
        ))

    db = t.add_resource(
        DBInstance(
            "RDSHelloWorldApp",
            DBName=Join("", [Ref(dbName), env]),
            DBInstanceIdentifier=Join("", [Ref(dbName), env]),
            EnableIAMDatabaseAuthentication=True,
            PubliclyAccessible=True,
            AllocatedStorage=Ref(dbAllocatedStorage),
            DBInstanceClass=Ref(dbType),
            Engine="postgres",
            EngineVersion="10.4",
            MasterUsername=Ref(dbUser),
            MasterUserPassword=Ref(dbPassword),
            DBSubnetGroupName=Ref(subnetGroup),
            VPCSecurityGroups=[Ref(rdsSg)],
        ))

    t.add_output(
        Output("RDSConnectionString",
               Description="Connection string for database",
               Value=GetAtt("RDSHelloWorldApp", "Endpoint.Address")))

    if (bootstrap):
        return t

    #### INSTANCE SECTION ####
    keyName = t.add_parameter(
        Parameter(
            "KeyName",
            Type="String",
            Description="Name of an existing EC2 KeyPair to enable SSH access",
            MinLength="1",
            AllowedPattern="[\x20-\x7E]*",
            MaxLength="255",
            ConstraintDescription="can contain only ASCII characters.",
        ))

    scaleCapacityMin = t.add_parameter(
        Parameter(
            "ScaleCapacityMin",
            Default="1",
            Type="String",
            Description="Number of api servers to run",
        ))

    scaleCapacityMax = t.add_parameter(
        Parameter(
            "ScaleCapacityMax",
            Default="1",
            Type="String",
            Description="Number of api servers to run",
        ))

    scaleCapacityDesired = t.add_parameter(
        Parameter(
            "ScaleCapacityDesired",
            Default="1",
            Type="String",
            Description="Number of api servers to run",
        ))

    amiId = t.add_parameter(
        Parameter(
            "AmiId",
            Type="String",
            Default="ami-09693313102a30b2c",
            Description="The AMI id for the api instances",
        ))

    instanceType = t.add_parameter(
        Parameter("InstanceType",
                  Description="WebServer EC2 instance type",
                  Type="String",
                  Default="t2.medium",
                  AllowedValues=[
                      "t2.nano", "t2.micro", "t2.small", "t2.medium",
                      "t2.large", "m3.medium", "m3.large", "m3.xlarge",
                      "m3.2xlarge", "m4.large", "m4.xlarge", "m4.2xlarge",
                      "m4.4xlarge", "m4.10xlarge", "c4.large", "c4.xlarge",
                      "c4.2xlarge", "c4.4xlarge", "c4.8xlarge"
                  ],
                  ConstraintDescription="must be a valid EC2 instance type."))

    assumeRole = t.add_resource(
        Role("AssumeRole",
             AssumeRolePolicyDocument=json.loads("""\
{
  "Version": "2012-10-17",
  "Statement": [
    {
    "Action": "sts:AssumeRole",
    "Principal": {
      "Service": "ec2.amazonaws.com"
    },
    "Effect": "Allow",
    "Sid": ""
    }
  ]
}\
""")))

    instanceProfile = t.add_resource(
        InstanceProfile("InstanceProfile", Roles=[Ref(assumeRole)]))

    rolePolicyType = t.add_resource(
        PolicyType("RolePolicyType",
                   Roles=[Ref(assumeRole)],
                   PolicyName=Join("", ["CloudWatchHelloWorld", "-", env]),
                   PolicyDocument=json.loads("""\
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:DescribeLogStreams",
        "logs:PutLogEvents"
      ],
    "Effect": "Allow",
    "Resource": [
        "arn:aws:logs:*:*:*"
      ]
    }
  ]
}\
""")))

    appPassword = t.add_parameter(
        Parameter(
            "AppPassword",
            NoEcho=True,
            Description="The Password for the app user",
            Type="String",
            MinLength="8",
            MaxLength="41",
            AllowedPattern="[a-zA-Z0-9]*",
            ConstraintDescription="must contain only alphanumeric characters.")
    )

    launchConfig = t.add_resource(
        LaunchConfiguration(
            "LaunchConfiguration",
            Metadata=autoscaling.Metadata(
                cloudformation.Init({
                    "config":
                    cloudformation.InitConfig(files=cloudformation.InitFiles({
                        "/home/app/environment":
                        cloudformation.InitFile(content=Join(
                            "", [
                                "SPRING_DATASOURCE_URL=", "jdbc:postgresql://",
                                GetAtt("RDSHelloWorldApp", "Endpoint.Address"),
                                ":5432/HelloWorldApp" + env +
                                "?currentSchema=hello_world", "\n",
                                "SPRING_DATASOURCE_USERNAME=app", "\n",
                                "SPRING_DATASOURCE_PASSWORD="******"\n",
                                "SPRING_PROFILES_ACTIVE=", env, "\n"
                            ]),
                                                mode="000600",
                                                owner="app",
                                                group="app")
                    }), )
                }), ),
            UserData=Base64(
                Join('', [
                    "#!/bin/bash\n", "/opt/aws/bin/cfn-init",
                    "    --resource LaunchConfiguration", "    --stack ",
                    Ref("AWS::StackName"), "    --region ",
                    Ref("AWS::Region"), "\n", "/opt/aws/bin/cfn-signal -e $? ",
                    "         --stack ", {
                        "Ref": "AWS::StackName"
                    }, "         --resource AutoscalingGroup ",
                    "         --region ", {
                        "Ref": "AWS::Region"
                    }, "\n"
                ])),
            ImageId=Ref(amiId),
            KeyName=Ref(keyName),
            IamInstanceProfile=Ref(instanceProfile),
            BlockDeviceMappings=[
                ec2.BlockDeviceMapping(DeviceName="/dev/xvda",
                                       Ebs=ec2.EBSBlockDevice(VolumeSize="8")),
            ],
            SecurityGroups=[Ref(instanceSg)],
            InstanceType=Ref(instanceType),
            AssociatePublicIpAddress='True',
        ))

    applicationElasticLB = t.add_resource(
        elb.LoadBalancer("ApplicationElasticLB",
                         Name="ApplicationElasticLB-" + env,
                         Scheme="internet-facing",
                         Type="application",
                         SecurityGroups=[Ref(loadBalancerSg)],
                         Subnets=[Ref(subnet1), Ref(subnet2)]))

    targetGroup = t.add_resource(
        elb.TargetGroup("TargetGroupHelloWorld",
                        HealthCheckProtocol="HTTP",
                        HealthCheckTimeoutSeconds="15",
                        HealthyThresholdCount="5",
                        Matcher=elb.Matcher(HttpCode="200,404"),
                        Port="8000",
                        Protocol="HTTP",
                        UnhealthyThresholdCount="3",
                        TargetGroupAttributes=[
                            elb.TargetGroupAttribute(
                                Key="deregistration_delay.timeout_seconds",
                                Value="120",
                            )
                        ],
                        VpcId=Ref(vpc)))

    listener = t.add_resource(
        elb.Listener("Listener",
                     Port="80",
                     Protocol="HTTP",
                     LoadBalancerArn=Ref(applicationElasticLB),
                     DefaultActions=[
                         elb.Action(Type="forward",
                                    TargetGroupArn=Ref(targetGroup))
                     ]))

    t.add_output(
        Output("URL",
               Description="URL of the sample website",
               Value=Join("",
                          ["http://",
                           GetAtt(applicationElasticLB, "DNSName")])))

    autoScalingGroup = t.add_resource(
        AutoScalingGroup(
            "AutoscalingGroup",
            DesiredCapacity=Ref(scaleCapacityDesired),
            LaunchConfigurationName=Ref(launchConfig),
            MinSize=Ref(scaleCapacityMin),
            MaxSize=Ref(scaleCapacityMax),
            VPCZoneIdentifier=[Ref(subnet1), Ref(subnet2)],
            TargetGroupARNs=[Ref(targetGroup)],
            HealthCheckType="ELB",
            HealthCheckGracePeriod=360,
            UpdatePolicy=UpdatePolicy(
                AutoScalingReplacingUpdate=AutoScalingReplacingUpdate(
                    WillReplace=True, ),
                AutoScalingRollingUpdate=AutoScalingRollingUpdate(
                    PauseTime='PT5M',
                    MinInstancesInService="1",
                    MaxBatchSize='1',
                    WaitOnResourceSignals=True)),
            CreationPolicy=CreationPolicy(ResourceSignal=ResourceSignal(
                Timeout="PT15M", Count=Ref(scaleCapacityDesired)))))

    # print(t.to_json())
    return t
Example #7
0
    def generate_app_load_balancer(self, lb_name, typ, port, cert_arn, log_bucket):

        lb_name = self.cfn_name(lb_name)

        if len(lb_name) >= 32:
            alb_name = lb_name[0:31]
        else:
            alb_name = lb_name

        if len(lb_name + 'TG') >= 32:
            tg_name = '{}TG'.format(lb_name[0:29])
        else:
            tg_name = '{}TG'.format(lb_name)

        if typ not in ['internal', 'internet-facing']:
            raise NameError("Load balancer type must be of type internal, internet-facing")

        # Use the system security groups (automatic) if internal, else use the limited external security group
        sg = self.security_groups if typ == 'internal' else [Ref(self.elb_external_security_group)]

        _alb = elasticloadbalancingv2.LoadBalancer(
            alb_name,
            Name=alb_name,
            IpAddressType='ipv4',
            LoadBalancerAttributes=[
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='access_logs.s3.enabled',
                    Value='true'
                ),
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='access_logs.s3.bucket',
                    Value=log_bucket
                ),
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='access_logs.s3.prefix',
                    Value="ELB/{}/{}".format(self.env, lb_name)
                ),
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='deletion_protection.enabled',
                    Value='false'
                ),
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='idle_timeout.timeout_seconds',
                    Value='60'
                ),
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='routing.http.drop_invalid_header_fields.enabled',
                    Value='false'
                ),
                elasticloadbalancingv2.LoadBalancerAttributes(
                    Key='routing.http2.enabled',
                    Value='true'
                )
            ],
            Scheme=typ,
            SecurityGroups=sg,
            Subnets=[s['SubnetId'] for s in self.get_subnets('private' if typ == 'internal' else 'public')],
            Type='application',
            Tags=self.get_tags(
                service_override="InternalALB" if typ == 'internal' else "ExternalALB",
                role_override=lb_name
            ) + [ec2.Tag('Name', lb_name)]
        )

        _target_group = elasticloadbalancingv2.TargetGroup(
            tg_name,
            Name=tg_name,
            HealthCheckIntervalSeconds=30,
            HealthCheckPath='/ping',
            HealthCheckPort=port,
            HealthCheckProtocol='HTTP',
            HealthCheckTimeoutSeconds=5,
            HealthyThresholdCount=5,
            UnhealthyThresholdCount=2,
            Matcher=elasticloadbalancingv2.Matcher(
                HttpCode='200'
            ),
            Port=port,
            Protocol='HTTP',
            TargetGroupAttributes=[
                elasticloadbalancingv2.TargetGroupAttribute(
                    Key='deregistration_delay.timeout_seconds',
                    Value='300'
                ),
                elasticloadbalancingv2.TargetGroupAttribute(
                    Key='stickiness.enabled',
                    Value='false'
                ),
                elasticloadbalancingv2.TargetGroupAttribute(
                    Key='stickiness.type',
                    Value='lb_cookie'
                ),
                elasticloadbalancingv2.TargetGroupAttribute(
                    Key='load_balancing.algorithm.type',
                    Value='least_outstanding_requests'
                )
            ],
            TargetType='instance',
            VpcId=self.vpc_id,
            Tags=self.get_tags(
                service_override="InternalALB" if typ == 'internal' else "ExternalALB",
                role_override=lb_name
            ) + [ec2.Tag('Name', '{}TG'.format(lb_name))]
        )

        _listener_80 = self.add_resource(elasticloadbalancingv2.Listener(
            '{}80Listener'.format(lb_name),
            Port='80',
            Protocol='HTTP',
            LoadBalancerArn=Ref(_alb),
            DefaultActions=[
                elasticloadbalancingv2.Action(
                    Type='redirect',
                    RedirectConfig=elasticloadbalancingv2.RedirectConfig(
                        Host='#{host}',
                        Path='/#{path}',
                        Port='443',
                        Protocol='HTTPS',
                        Query='#{query}',
                        StatusCode='HTTP_301'
                    )
                )
            ],
        ))
        _listener_443 = self.add_resource(elasticloadbalancingv2.Listener(
            '{}443Listener'.format(lb_name),
            Port='443',
            Protocol='HTTPS',
            LoadBalancerArn=Ref(_alb),
            SslPolicy='ELBSecurityPolicy-2016-08',
            Certificates=[
                elasticloadbalancingv2.Certificate(
                    CertificateArn=cert_arn
                )
            ],
            DefaultActions=[
                elasticloadbalancingv2.Action(
                    Type='forward',
                    TargetGroupArn=Ref(_target_group)
                )
            ],
        ))
        return _alb, _target_group
Example #8
0
    def add_ec2(self, ami_name, instance_type, asg_size, cidr, hosted_zone):
        """
        Helper method creates ingress given a source cidr range and a set of
        ports
        @param ami_name [string] Name of the AMI for launching the app
        @param instance_type [string] Instance for the application
        @param asg_size [int] Sets the size of the asg
        @param cidr [string] Range of addresses for this vpc
        @param hosted_zone [string] Name of the hosted zone the elb will be
        mapped to
        """
        print "Creating EC2"

        self.internal_security_group = self.add_sg_with_cidr_port_list(
            "ASGSG",
            "Security Group for EC2",
            'vpcId',
            cidr,
            [{"443": "443"}, {"80": "80"}]
        )

        self.public_lb_security_group = self.add_sg_with_cidr_port_list(
            "ELBSG",
            "Security Group for accessing EC2 publicly",
            'vpcId',
            '0.0.0.0/0',
            [{"443": "443"}]
        )

        name = self.env_name.replace('-', '')

        public_subnet_count = len(self._subnets.get('public').get('public'))
        public_subnets = [{'Ref': x} for x in ["publicAZ%d" % n for n in range(0, public_subnet_count)]]
        public_alb = self.add_resource(alb.LoadBalancer(
            "PublicALB",
            Scheme='internet-facing',
            Subnets=public_subnets,
            SecurityGroups=[Ref(sg) for sg in [self.public_lb_security_group]]
        ))

        target_group = self.add_resource(alb.TargetGroup(
            "AppTargetGroup80",
            Port=80,
            Protocol="HTTP",
            VpcId=self.vpc_id,
            TargetGroupAttributes=[alb.TargetGroupAttribute(Key="stickiness.enabled", Value='true'),
                                   alb.TargetGroupAttribute(Key="stickiness.type", Value='lb_cookie'),
                                   alb.TargetGroupAttribute(Key="stickiness.lb_cookie.duration_seconds", Value='3600')]
        ))
        certificate = 'arn:aws:acm:us-east-1:422548007577:certificate/d9b8fbd2-13bb-4d6e-aba4-53061b1580f9'
        alb_ssl_listener = self.add_resource(alb.Listener(
            "ALBListner",
            Port=443,
            Certificates=[alb.Certificate(CertificateArn=certificate)],
            Protocol="HTTPS",
            DefaultActions=[alb.Action(
                Type="forward",
                TargetGroupArn=Ref(target_group))],
            LoadBalancerArn=Ref(public_alb)
        ))

        self.add_elb_dns_alias(public_alb, '', hosted_zone)
        policies = ['cloudwatchlogs']
        policies_for_profile = [self.get_policy(policy, 'EC2') for policy in policies]

        asg = self.add_asg(
            "EC2",
            min_size=asg_size,
            max_size=6,
            ami_name=ami_name,
            # load_balancer=public_elb,
            instance_profile=self.add_instance_profile(name, policies_for_profile, name),
            instance_type=instance_type,
            security_groups=['commonSecurityGroup', Ref(self.internal_security_group)],
            subnet_layer='private',
            update_policy=UpdatePolicy(
                AutoScalingRollingUpdate=AutoScalingRollingUpdate(
                    PauseTime='PT5M',
                    MinInstancesInService=1,
                    # The maximum number of instances that are terminated at a given time, left at 1 to ease into updates.
                    # Can be increased at a later time
                    MaxBatchSize='1'
                )
            ),
            user_data=Base64(Join('', [
                '#!/bin/bash\n',
                'echo Good to go'
            ])))

        asg.resource['Properties']['TargetGroupARNs'] = [Ref(target_group)]

        # Cluster Memory Scaling policies
        asg_scale_up_policy = self.add_resource(
            autoscaling.ScalingPolicy(
                name + 'ScaleUpPolicy',
                AdjustmentType='ChangeInCapacity',
                AutoScalingGroupName=Ref(asg),
                Cooldown=300,
                ScalingAdjustment=1
            )
        )

        # ELB latency above a threshold
        self.add_resource(
            cloudwatch.Alarm(
                name + 'LatencyHigh',
                MetricName='Latency',
                ComparisonOperator='GreaterThanThreshold',
                Period=300,
                EvaluationPeriods=1,
                Statistic='Average',
                Namespace='AWS/ELB',
                AlarmDescription=name + 'LatencyHigh',
                Dimensions=[cloudwatch.MetricDimension(Name='LoadBalancerName', Value=Ref(public_alb))],
                Threshold='6',
                AlarmActions=[
                  Ref(asg_scale_up_policy),
                  'arn:aws:sns:us-east-1:422548007577:notify-pat'
                ]
            )
        )
                          elbv2.TargetDescription(
                              Id=Ref(param_instance_id),
                              Port='80',
                          )
                      ],
                      HealthCheckIntervalSeconds='15',
                      HealthCheckPath='/',
                      HealthCheckPort='80',
                      HealthCheckProtocol='HTTP',
                      HealthCheckTimeoutSeconds='5',
                      HealthyThresholdCount='3',
                      UnhealthyThresholdCount='5',
                      Matcher=elbv2.Matcher(HttpCode='200'),
                      TargetGroupAttributes=[
                          elbv2.TargetGroupAttribute(
                              Key='deregistration_delay.timeout_seconds',
                              Value='20')
                      ]))

http_listener = t.add_resource(
    elbv2.Listener(
        'HttpListener',
        DefaultActions=[
            elbv2.Action(TargetGroupArn=Ref(targetgroup), Type='forward')
        ],
        LoadBalancerArn=Ref(load_balancer),
        Port='80',
        Protocol='HTTP',
    ))

https_listener = t.add_resource(
Example #10
0
File: ac3.py Project: ghac3/cfwp
    elasticloadbalancingv2.LoadBalancer(
        "ELB",
        Name='ELB',
        Scheme='internet-facing',
        Subnets=[Ref('pSubnet1'), Ref('pSubnet2')],
        SecurityGroups=[Ref('ELBSG')]))
tg = template.add_resource(
    elasticloadbalancingv2.TargetGroup(
        "Tg",
        HealthCheckIntervalSeconds="20",
        HealthCheckProtocol="HTTP",
        HealthCheckTimeoutSeconds="10",
        HealthyThresholdCount="2",
        #  Matcher=elasticloadbalancingv2.Matcher(HttpCode="200"), #  Seems that wordpress/nginx returns 302.
        TargetGroupAttributes=[
            elasticloadbalancingv2.TargetGroupAttribute(
                Key='stickiness.enabled', Value='true')
        ],
        Name="WordPressTarget",
        Port=80,
        Protocol="HTTP",
        UnhealthyThresholdCount="3",
        VpcId=Ref('pVPCID')))
listener = template.add_resource(
    elasticloadbalancingv2.Listener("Listener",
                                    Port="80",
                                    Protocol="HTTP",
                                    LoadBalancerArn=Ref('ELB'),
                                    DefaultActions=[
                                        elasticloadbalancingv2.Action(
                                            Type="forward",
                                            TargetGroupArn=Ref('Tg'))
Example #11
0
    def elbv2_target_group(self,
                           name,
                           protocol,
                           port,
                           vpc_id,
                           health_check_details={},
                           matcher=None,
                           target_group_attributes=False,
                           targets=[]):
        """
        Create ELBv2 Target Group

        :param name: Name of the target group
        :param protocol: Protocol
        :param port: Port
        :param vpc_id: VPC id
        :param health_check_details: Array of health check detail
        :param matcher: HTTP code to use when checking for health check response
        :param target_group_attributes: Additional target group attributes
        :param targets: Targets, if applicable
        :return: Target Group CFN object
        """

        target_group = elbv2.TargetGroup(
            name,
            Protocol=protocol,
            Port=port,
            VpcId=vpc_id,
            HealthCheckProtocol=health_check_details["health_check_protocol"],
            HealthCheckPort=health_check_details["health_check_port"],
            HealthCheckIntervalSeconds=health_check_details[
                "health_check_interval"],
            HealthyThresholdCount=health_check_details["healthy_threshold"],
            UnhealthyThresholdCount=health_check_details[
                "unhealthy_threshold"],
            Targets=targets)

        if health_check_details.get("health_check_path"):
            target_group.HealthCheckPath = health_check_details[
                "health_check_path"]

        if health_check_details.get("health_check_timeout"):
            target_group.HealthCheckTimeoutSeconds = health_check_details[
                "health_check_timeout"]

        if matcher:
            target_group.Matcher = elbv2.Matcher(HttpCode=matcher)

        if target_group_attributes:
            attributes = []
            for attr in target_group_attributes:
                attributes.append(
                    elbv2.TargetGroupAttribute(Key=attr['key'],
                                               Value=attr['value']))
            target_group.TargetGroupAttributes = attributes

        self.template.add_resource(target_group)
        self.template.add_output(
            Output(name,
                   Value=Ref(name),
                   Description="Target Group {} ARN".format(name),
                   Export=Export(Sub("${AWS::StackName}-" + name))))

        return target_group
Example #12
0
"""
target_group = t.add_resource(elasticloadbalancingv2.TargetGroup(
    "TargetGroup1",
    Port=Ref(container_port),
    Protocol="HTTP",
    HealthCheckPath=Ref(health_check_path),
    HealthCheckIntervalSeconds="30",
    HealthCheckProtocol="HTTP",
    HealthCheckTimeoutSeconds="10",
    HealthyThresholdCount="4",
    Matcher=elasticloadbalancingv2.Matcher(HttpCode="200,302"),
    UnhealthyThresholdCount="3",
    VpcId=ImportValue(Sub("${NetworkStack}-Vpc")),
    TargetGroupAttributes=[
        elasticloadbalancingv2.TargetGroupAttribute(
            Key="deregistration_delay.timeout_seconds",
            Value="10",
        ),
    ],
    Tags=[{
        "Key": "TargetGroupName",
        "Value": Join("", ["Tg-", Ref(container_name)])
    }]
))

"""
Task definition
"""
task_definition = t.add_resource(ecs.TaskDefinition(
    "TaskDefinition",
    DependsOn=log_group.title,
    TaskRoleArn=GetAtt(task_role, "Arn"),