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)
            )
        ]
Esempio n. 2
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        listenerrule = template.add_resource(
            elasticloadbalancingv2.ListenerRule(
                'ListenerRule',
                Actions=[
                    elasticloadbalancingv2.Action(
                        TargetGroupArn=variables['TargetGroupArn'].ref,
                        Type='forward'
                    )
                ],
                Conditions=[
                    elasticloadbalancingv2.Condition(
                        Field=variables['Condition'].ref,
                        Values=[variables['Value'].ref]
                    )
                ],
                ListenerArn=variables['ListenerArn'].ref,
                Priority=variables['Priority'].ref
            )
        )

        template.add_output(Output(
            "{}Arn".format(listenerrule.title),
            Description="ARN of the Listener Rule",
            Value=Ref(listenerrule),
            Export=Export(
                Sub('${AWS::StackName}-%sArn' % listenerrule.title)
            )
        ))
Esempio n. 3
0
def create_loadbalancer():
    return [
        elb.LoadBalancer(
            'tlsFrontend',
            SecurityGroups=[Ref('secgrpLoadBalancer')],
            Subnets=[Ref('subnetA'), Ref('subnetB')],
            Tags=_tags(),
        ),
        elb.Listener(
            'tlsFrontendListener',
            Certificates=[
                elb.Certificate(CertificateArn=Ref('certificateArn')),
            ],
            DefaultActions=[
                elb.Action(TargetGroupArn=Ref('tlsFrontendApplication'),
                           Type='forward'),
            ],
            LoadBalancerArn=Ref('tlsFrontend'),
            Port=443,
            Protocol='HTTPS',
        ),
        elb.ListenerRule(
            'tlsFrontendJenkinsRule',
            Actions=[
                elb.Action(TargetGroupArn=Ref('tlsFrontendJenkins'),
                           Type='forward'),
            ],
            Conditions=[
                elb.Condition(Field='host-header',
                              Values=[_subdomain_for_jenkins()]),
            ],
            ListenerArn=Ref('tlsFrontendListener'),
            Priority=1,
        ),
        elb.TargetGroup(
            'tlsFrontendApplication',
            HealthCheckIntervalSeconds=300,
            HealthCheckPath='/health',
            Port=80,
            Protocol='HTTP',
            Tags=_tags(),
            Targets=[
                elb.TargetDescription(Id=Ref('devserver'), Port=80),
            ],
            VpcId=Ref('vpc'),
        ),
        elb.TargetGroup(
            'tlsFrontendJenkins',
            HealthCheckIntervalSeconds=300,
            HealthCheckPath='/robots.txt',
            Port=8080,
            Protocol='HTTP',
            Tags=_tags(),
            Targets=[
                elb.TargetDescription(Id=Ref('devserver'), Port=8080),
            ],
            VpcId=Ref('vpc'),
        ),
    ]
Esempio n. 4
0
    def elbv2_listener_rule(self, name, actions, conditions, listener_arn,
                            priority):
        """
        Create ELBv2 listener rule

        :param name: Name to assign to the rule
        :param actions: Listener actions,
        :param conditions: Conditions (i.e application layer rules)
        :param listener_arn: ARN of the listener
        :param priority: Rule priority, for when there are multiple rules.
        """
        self.template.add_resource(
            elbv2.ListenerRule(name,
                               Actions=actions,
                               Conditions=conditions,
                               ListenerArn=listener_arn,
                               Priority=priority))
Esempio n. 5
0
 def create_listener_rule(self):
     t = self.template
     listener_rule = t.add_resource(
         elb.ListenerRule(
             "ListenerRule",
             ListenerArn=self.vars['DefaultListener'],
             Priority=1,
             Actions=[
                 elb.Action(Type="forward",
                            TargetGroupArn=Ref(self.target_group))
             ],
             Conditions=[
                 elb.Condition(
                     Field="path-pattern",
                     Values=['/'],
                 )
             ],
         ))
     return listener_rule
Esempio n. 6
0
def create_alb_listener_rule(stack,
                             name,
                             listener,
                             condition,
                             target_group,
                             priority=1,
                             condition_field=''):
    """Add ALB Listener Rule Resource."""

    return stack.stack.add_resource(
        alb.ListenerRule(
            '{0}ListenerRule'.format(name),
            Condition=condition_field,
            ListenerArn=listener,
            Conditions=[
                alb.Condition(Field=condition['field'],
                              Values=condition['values'])
            ],
            Actions=[alb.Action(Type='forward', TargetGroupArn=target_group)],
            Priority=priority))
Esempio n. 7
0
 def gen_listener_rule(self):
     self.listener_rule = elasticloadbalancingv2.ListenerRule(
         "ListenerRule",
         Actions=[
             elasticloadbalancingv2.Action(Type="forward",
                                           TargetGroupArn=Ref(
                                               self.target_group))
         ],
         Conditions=[
             elasticloadbalancingv2.Condition(
                 Field="path-pattern",
                 PathPatternConfig=elasticloadbalancingv2.PathPatternConfig(
                     Values=["/demo/*", "/demo"]),
             )
         ],
         ListenerArn=self.import_value("load-balancer",
                                       "LoadBalancerListenerHTTP"),
         Priority=10,
     )
     self.template.add_resource(self.listener_rule)
Esempio n. 8
0
    def handle(self, chain_context):

        template = chain_context.template

        if not (self.path_pattern or self.host_pattern):
            raise RuntimeError(
                "with_listener_rule() requires one of: path_pattern, host_pattern"
            )

        routing_condition = None
        if self.path_pattern:
            routing_condition = alb.Condition(
                Field="path-pattern",
                Values=[self.path_pattern],
            )
        # TODO: support host headers someday
        # elif self.host_pattern:
        #     routing_condition = alb.Condition(
        #         Field="host-header",
        #         Values=[
        #             chain_context.instance_name,
        #             "-",
        #             What do we put here?
        #             ".",
        #             self.base_domain_name
        #         ]
        #     )

        listener_rule = alb.ListenerRule(
            self.name,
            ListenerArn=self.alb_listener_rule,
            Conditions=[routing_condition],
            Actions=[
                alb.Action(Type="forward",
                           TargetGroupArn=Ref(
                               chain_context.metadata[META_TARGET_GROUP_NAME]))
            ],
            Priority=self.priority,
        )

        template.add_resource(listener_rule)
Esempio n. 9
0
    def add_resources_and_outputs(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        for rule in variables['Rules']:
            listenerrule = template.add_resource(
                elasticloadbalancingv2.ListenerRule(
                    'ListenerRule{p}'.format(p=rule['Priority']),
                    Actions=[
                        elasticloadbalancingv2.Action(
                            TargetGroupArn=rule['TargetGroupArn'],
                            Type='forward'
                        )
                    ],
                    Conditions=[
                        elasticloadbalancingv2.Condition(
                            Field=rule['Condition'],
                            Values=[rule['Value']]
                        )
                    ],
                    ListenerArn=variables['ListenerArn'].ref,
                    Priority=rule['Priority']
                )
            )

            template.add_output(
                Output(
                    '{}Arn'.format(listenerrule.title),
                    Description='ARN of the Listener Rule {}'.format(
                        rule['Priority']
                    ),
                    Export=Export(
                        Sub('${AWS::StackName}-%sArn' % listenerrule.title)
                    ),
                    Value=Ref(listenerrule),
                )
            )
Esempio n. 10
0
                      ]))

ElasticLoadBalancingV2ListenerRule = template.add_resource(
    elasticloadbalancingv2.ListenerRule(
        'ElasticLoadBalancingV2ListenerRule',
        Priority='1',
        ListenerArn=
        'arn:aws:elasticloadbalancing:us-east-2:445114057331:listener/app/my-service-lb/39baed772591d6c0/930c98eb2dcb4690',
        Conditions=[
            elasticloadbalancingv2.Condition(
                Field='path-pattern',
                Values=['/api/currency-exchange-microservice/*'])
        ],
        Actions=[
            elasticloadbalancingv2.Action(
                Type='forward',
                TargetGroupArn=
                'arn:aws:elasticloadbalancing:us-east-2:445114057331:targetgroup/currencyexchangeservicetg/1d71df4075d5ad16',
                ForwardConfig={
                    "TargetGroups": [{
                        'TargetGroupArn':
                        'arn:aws:elasticloadbalancing:us-east-2:445114057331:targetgroup/currencyexchangeservicetg/1d71df4075d5ad16',
                        'Weight': 1
                    }],
                    "TargetGroupStickinessConfig": {
                        'Enabled': False
                    }
                })
        ]))

ElasticLoadBalancingV2ListenerRule2 = template.add_resource(
    elasticloadbalancingv2.ListenerRule(
Esempio n. 11
0
def main():
    template = Template()
    template.add_version("2010-09-09")

    template.add_description(
        "AWS CloudFormation Sample Template: ELB with 2 EC2 instances")

    AddAMI(template)

    # Add the Parameters
    keyname_param = template.add_parameter(
        Parameter(
            "KeyName",
            Type='AWS::EC2::KeyPair::KeyName',
            Default="ansible-key",
            Description="Name of an existing EC2 KeyPair to "
            "enable SSH access to the instance",
        ))

    template.add_parameter(
        Parameter(
            "InstanceType",
            Type="String",
            Description="WebServer EC2 instance type",
            Default="t2.micro",
            AllowedValues=["t1.micro", "t2.micro"],
            ConstraintDescription="must be a valid EC2 instance type.",
        ))

    webport_param = template.add_parameter(
        Parameter(
            "WebServerPort",
            Type="String",
            Default="8888",
            Description="TCP/IP port of the web server",
        ))

    web2_param = template.add_parameter(
        Parameter(
            "ApiServerPort",
            Type="String",
            Default="8889",
            Description="TCP/IP port of the api server",
        ))

    subnetA = template.add_parameter(
        Parameter("subnetA",
                  Type="List<AWS::EC2::Subnet::Id>",
                  Description="Choose Subnets"))

    VpcId = template.add_parameter(
        Parameter("VpcId", Type="AWS::EC2::VPC::Id", Description="Choose VPC"))

    # Define the instance security group
    instance_sg = template.add_resource(
        ec2.SecurityGroup(
            "InstanceSecurityGroup",
            GroupDescription="Enable SSH and HTTP access on the inbound port",
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort="22",
                    ToPort="22",
                    CidrIp="0.0.0.0/0",
                ),
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort=Ref(webport_param),
                    ToPort=Ref(webport_param),
                    CidrIp="0.0.0.0/0",
                ),
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort=Ref(web2_param),
                    ToPort=Ref(web2_param),
                    CidrIp="0.0.0.0/0",
                ),
            ]))

    # Add the web server instance
    WebInstance = template.add_resource(
        ec2.Instance(
            "WebInstance",
            SecurityGroups=[Ref(instance_sg)],
            KeyName=Ref(keyname_param),
            InstanceType=Ref("InstanceType"),
            ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
            UserData=Base64(
                Join('', [
                    '#!/bin/bash\n',
                    'sudo yum -y update\n',
                    'sudo yum install -y httpd php\n',
                    'sudo sed -i "42s/Listen 80/Listen 8888/" /etc/httpd/conf/httpd.conf\n',
                    'sudo service httpd restart \n',
                    'Ref(webport_param)',
                ]))))

    # Add the api server instance
    ApiInstance = template.add_resource(
        ec2.Instance(
            "ApiInstance",
            SecurityGroups=[Ref(instance_sg)],
            KeyName=Ref(keyname_param),
            InstanceType=Ref("InstanceType"),
            ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
            UserData=Base64(
                Join('', [
                    '#!/bin/bash\n',
                    'sudo yum -y update\n',
                    'sudo yum install -y httpd php\n',
                    'sudo sed -i "42s/Listen 80/Listen 8889/" /etc/httpd/conf/httpd.conf\n',
                    'sudo service httpd restart \n',
                    'Ref(web2_param)',
                ]))))

    # Add the application ELB
    ApplicationElasticLB = template.add_resource(
        elb.LoadBalancer("ApplicationElasticLB",
                         Name="ApplicationElasticLB",
                         Scheme="internet-facing",
                         Subnets=Ref("subnetA")))

    TargetGroupWeb = template.add_resource(
        elb.TargetGroup("TargetGroupWeb",
                        HealthCheckIntervalSeconds="30",
                        HealthCheckProtocol="HTTP",
                        HealthCheckTimeoutSeconds="10",
                        HealthyThresholdCount="4",
                        Matcher=elb.Matcher(HttpCode="200"),
                        Name="WebTarget",
                        Port=Ref(webport_param),
                        Protocol="HTTP",
                        Targets=[
                            elb.TargetDescription(Id=Ref(WebInstance),
                                                  Port=Ref(webport_param))
                        ],
                        UnhealthyThresholdCount="3",
                        VpcId=Ref(VpcId)))

    TargetGroupApi = template.add_resource(
        elb.TargetGroup("TargetGroupApi",
                        HealthCheckIntervalSeconds="30",
                        HealthCheckProtocol="HTTP",
                        HealthCheckTimeoutSeconds="10",
                        HealthyThresholdCount="4",
                        Matcher=elb.Matcher(HttpCode="200"),
                        Name="ApiTarget",
                        Port=Ref(web2_param),
                        Protocol="HTTP",
                        Targets=[
                            elb.TargetDescription(Id=Ref(ApiInstance),
                                                  Port=Ref(web2_param))
                        ],
                        UnhealthyThresholdCount="3",
                        VpcId=Ref(VpcId)))

    Listener = template.add_resource(
        elb.Listener("Listener",
                     Port="80",
                     Protocol="HTTP",
                     LoadBalancerArn=Ref(ApplicationElasticLB),
                     DefaultActions=[
                         elb.Action(Type="forward",
                                    TargetGroupArn=Ref(TargetGroupWeb))
                     ]))

    template.add_resource(
        elb.ListenerRule("ListenerRuleApi",
                         ListenerArn=Ref(Listener),
                         Conditions=[
                             elb.Condition(Field="path-pattern",
                                           Values=["/api/*"])
                         ],
                         Actions=[
                             elb.Action(Type="forward",
                                        TargetGroupArn=Ref(TargetGroupApi))
                         ],
                         Priority="1"))

    template.add_output(
        Output("URL",
               Description="URL of the sample website",
               Value=Join("",
                          ["http://",
                           GetAtt(ApplicationElasticLB, "DNSName")])))
    print(template.to_json())
Esempio n. 12
0
def main():
    template = Template()

    subnetA = template.add_parameter(Parameter("subnetA", Type="String"))
    subnetB = template.add_parameter(Parameter("subnetB", Type="String"))

    alb = template.add_resource(
        elb.LoadBalancer(
            "ALB",
            Scheme="internet-facing",
            Subnets=[subnetA.ref(), subnetB.ref()],
        ))

    listener = template.add_resource(
        elb.Listener(
            "Listener",
            Port="80",
            Protocol="HTTP",
            LoadBalancerArn=alb.ref(),
            DefaultActions=[
                elb.Action(
                    Type="fixed-response",
                    FixedResponseConfig=elb.FixedResponseConfig(
                        StatusCode="200",
                        MessageBody=(
                            "This is a fixed response for the default "
                            "ALB action"),
                        ContentType="text/plain",
                    ),
                )
            ],
        ))

    template.add_resource([
        elb.ListenerRule(
            "ListenerRuleApi",
            ListenerArn=listener.ref(),
            Conditions=[
                elb.Condition(Field="host-header", Values=["api.example.com"]),
                elb.Condition(
                    Field="http-header",
                    HttpHeaderConfig=elb.HttpHeaderConfig(
                        HttpHeaderName="X-Action", Values=["Create"]),
                ),
                elb.Condition(
                    Field="path-pattern",
                    PathPatternConfig=elb.PathPatternConfig(Values=["/api/*"]),
                ),
                elb.Condition(
                    Field="http-request-method",
                    HttpRequestMethodConfig=elb.HttpRequestMethodConfig(
                        Values=["POST"]),
                ),
            ],
            Actions=[
                elb.Action(
                    Type="fixed-response",
                    FixedResponseConfig=elb.FixedResponseConfig(
                        StatusCode="200",
                        MessageBody=(
                            "This is a fixed response for any API POST "
                            "request with header X-Action: Create"),
                        ContentType="text/plain",
                    ),
                )
            ],
            Priority="10",
        ),
        elb.ListenerRule(
            "ListenerRuleWeb",
            ListenerArn=listener.ref(),
            Conditions=[
                elb.Condition(
                    Field="host-header",
                    HostHeaderConfig=elb.HostHeaderConfig(
                        Values=["www.example.com"]),
                ),
                elb.Condition(
                    Field="path-pattern",
                    PathPatternConfig=elb.PathPatternConfig(Values=["/web/*"]),
                ),
            ],
            Actions=[
                elb.Action(
                    Type="fixed-response",
                    FixedResponseConfig=elb.FixedResponseConfig(
                        StatusCode="200",
                        MessageBody=("This is a fixed response for any WEB "
                                     "request"),
                        ContentType="text/plain",
                    ),
                )
            ],
            Priority="20",
        ),
        elb.ListenerRule(
            "ListenerRuleMetrics",
            ListenerArn=listener.ref(),
            Conditions=[
                elb.Condition(Field="path-pattern", Values=["/metrics/*"])
            ],
            Actions=[
                elb.Action(
                    Type="redirect",
                    RedirectConfig=elb.RedirectConfig(StatusCode="HTTP_301",
                                                      Protocol="HTTPS",
                                                      Port="443"),
                )
            ],
            Priority="30",
        ),
        elb.ListenerRule(
            "ListenerRuleSourceIp",
            ListenerArn=listener.ref(),
            Conditions=[
                elb.Condition(
                    Field="source-ip",
                    SourceIpConfig=elb.SourceIpConfig(
                        Values=["52.30.12.16/28"]),
                )
            ],
            Actions=[
                elb.Action(
                    Type="fixed-response",
                    FixedResponseConfig=elb.FixedResponseConfig(
                        StatusCode="200",
                        MessageBody=("The request came from IP range "
                                     "52.30.12.16/28"),
                        ContentType="text/plain",
                    ),
                )
            ],
            Priority="40",
        ),
    ])

    print(template.to_json())
Esempio n. 13
0
    elb.Listener(
        "TestListener",
        Port="80",
        Protocol="HTTP",
        LoadBalancerArn=Ref(application_elb),
        DefaultActions=[elb.Action(
            Type="forward",
            TargetGroupArn=Ref(target_group_web)
        )]
    )
)

t.add_resource(
    elb.ListenerRule(
        "TestListenerRule",
        ListenerArn=Ref(elb_listener),
        Conditions=[elb.Condition(
            Field="path-pattern",
            Values=["/api/*"]
        )],
        Actions=[elb.Action(
            Type="forward",
            TargetGroupArn=Ref(target_group_api)
        )],
        Priority="1"
    )
)

print(t.to_json())

Esempio n. 14
0
        TargetType='ip',
        HealthCheckPath='/auth/realms/main',
        HealthCheckProtocol='HTTP',
        HealthCheckIntervalSeconds=240,
        HealthyThresholdCount=5,
        UnhealthyThresholdCount=5,
    ))

keycloakListenerRule = t.add_resource(
    elasticloadbalancingv2.ListenerRule(
        'KeycloakListenerRule',
        ListenerArn=ImportValue(Sub('${CoreStack}-ALB-Web-Listener')),
        Priority=10,
        Conditions=[
            elasticloadbalancingv2.Condition(Field='path-pattern',
                                             Values=['/auth', '/auth*'])
        ],
        Actions=[
            elasticloadbalancingv2.Action(
                Type='forward',
                TargetGroupArn=keycloakTargetGroup.Ref(),
            )
        ]))

keycloakTask = t.add_resource(
    ecs.TaskDefinition(
        'KeycloakTask',
        ContainerDefinitions=[
            ecs.ContainerDefinition(
                'KeycloakContainer',
                Name='keycloak',
                Image=Ref('KeycloakImage'),
Esempio n. 15
0
def main():
    template = Template()
    template.add_version("2010-09-09")

    template.add_description(
        "AWS CloudFormation Sample Template: ELB with 2 EC2 instances")

    AddAMI(template)

    # Add the Parameters
    keyname_param = template.add_parameter(Parameter(
        "KeyName",
        Type="String",
        Default="mark",
        Description="Name of an existing EC2 KeyPair to "
                    "enable SSH access to the instance",
    ))

    template.add_parameter(Parameter(
        "InstanceType",
        Type="String",
        Description="WebServer EC2 instance type",
        Default="m1.small",
        AllowedValues=[
            "t1.micro", "m1.small", "m1.medium", "m1.large", "m1.xlarge",
            "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "c1.medium", "c1.xlarge",
            "cc1.4xlarge", "cc2.8xlarge", "cg1.4xlarge"
        ],
        ConstraintDescription="must be a valid EC2 instance type.",
    ))

    webport_param = template.add_parameter(Parameter(
        "WebServerPort",
        Type="String",
        Default="8888",
        Description="TCP/IP port of the web server",
    ))

    apiport_param = template.add_parameter(Parameter(
        "ApiServerPort",
        Type="String",
        Default="8889",
        Description="TCP/IP port of the api server",
    ))

    subnetA = template.add_parameter(Parameter(
        "subnetA",
        Type="String",
        Default="subnet-096fd06d"
    ))

    subnetB = template.add_parameter(Parameter(
        "subnetB",
        Type="String",
        Default="subnet-1313ef4b"
    ))

    VpcId = template.add_parameter(Parameter(
        "VpcId",
        Type="String",
        Default="vpc-82c514e6"
    ))

    # Define the instance security group
    instance_sg = template.add_resource(
        ec2.SecurityGroup(
            "InstanceSecurityGroup",
            GroupDescription="Enable SSH and HTTP access on the inbound port",
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort="22",
                    ToPort="22",
                    CidrIp="0.0.0.0/0",
                ),
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort=Ref(webport_param),
                    ToPort=Ref(webport_param),
                    CidrIp="0.0.0.0/0",
                ),
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort=Ref(apiport_param),
                    ToPort=Ref(apiport_param),
                    CidrIp="0.0.0.0/0",
                ),
            ]
        )
    )

    # Add the web server instance
    WebInstance = template.add_resource(ec2.Instance(
        "WebInstance",
        SecurityGroups=[Ref(instance_sg)],
        KeyName=Ref(keyname_param),
        InstanceType=Ref("InstanceType"),
        ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
        UserData=Base64(Ref(webport_param)),
    ))

    # Add the api server instance
    ApiInstance = template.add_resource(ec2.Instance(
        "ApiInstance",
        SecurityGroups=[Ref(instance_sg)],
        KeyName=Ref(keyname_param),
        InstanceType=Ref("InstanceType"),
        ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
        UserData=Base64(Ref(apiport_param)),
    ))

    # Add the application ELB
    ApplicationElasticLB = template.add_resource(elb.LoadBalancer(
        "ApplicationElasticLB",
        Name="ApplicationElasticLB",
        Scheme="internet-facing",
        Subnets=[Ref(subnetA), Ref(subnetB)]
    ))

    TargetGroupWeb = template.add_resource(elb.TargetGroup(
        "TargetGroupWeb",
        HealthCheckIntervalSeconds="30",
        HealthCheckProtocol="HTTP",
        HealthCheckTimeoutSeconds="10",
        HealthyThresholdCount="4",
        Matcher=elb.Matcher(
            HttpCode="200"),
        Name="WebTarget",
        Port=Ref(webport_param),
        Protocol="HTTP",
        Targets=[elb.TargetDescription(
            Id=Ref(WebInstance),
            Port=Ref(webport_param))],
        UnhealthyThresholdCount="3",
        VpcId=Ref(VpcId)

    ))

    TargetGroupApi = template.add_resource(elb.TargetGroup(
        "TargetGroupApi",
        HealthCheckIntervalSeconds="30",
        HealthCheckProtocol="HTTP",
        HealthCheckTimeoutSeconds="10",
        HealthyThresholdCount="4",
        Matcher=elb.Matcher(
            HttpCode="200"),
        Name="ApiTarget",
        Port=Ref(apiport_param),
        Protocol="HTTP",
        Targets=[elb.TargetDescription(
            Id=Ref(ApiInstance),
            Port=Ref(apiport_param))],
        UnhealthyThresholdCount="3",
        VpcId=Ref(VpcId)

    ))

    Listener = template.add_resource(elb.Listener(
        "Listener",
        Port="80",
        Protocol="HTTP",
        LoadBalancerArn=Ref(ApplicationElasticLB),
        DefaultActions=[elb.Action(
            Type="forward",
            TargetGroupArn=Ref(TargetGroupWeb)
        )]
    ))

    template.add_resource(elb.ListenerRule(
        "ListenerRuleApi",
        ListenerArn=Ref(Listener),
        Conditions=[elb.Condition(
            Field="path-pattern",
            Values=["/api/*"])],
        Actions=[elb.Action(
            Type="forward",
            TargetGroupArn=Ref(TargetGroupApi)
        )],
        Priority="1"
    ))

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

    print(template.to_json())
        priority = services.index(s) + 1

        # Set a URL extension for non-prod environments
        if e == "prod":
            URLPathMod = ""
        else:
            URLPathMod = "{}.".format(e)

        t.add_resource(
            elb.ListenerRule(
                "{}{}ListenerRule".format(e, s),
                ListenerArn=Ref("{}Listener".format(e)),
                Conditions=[
                    elb.Condition(
                        Field="host-header",
                        Values=[Join("", [s, ".", URLPathMod, domain])])
                ],
                Actions=[
                    elb.Action(Type="forward",
                               TargetGroupArn=Ref("{}{}TargetGroup".format(
                                   e, s)))
                ],
                Priority=priority))

        t.add_resource(
            route53.RecordSetType("{}{}DNSRecord".format(e, s),
                                  HostedZoneName=Join("", [domain, "."]),
                                  Name=Join("",
                                            [s, ".", URLPathMod, domain, "."]),
                                  Type="A",
                                  AliasTarget=route53.AliasTarget(
                                      FindInMap("RegionZIDMap",
Esempio n. 17
0
#     )]
# ))
"""
Add the TargetGroup to a Listener on the ALB
 - path-pattern is given as a Parameter to this stack
"""
listener_rule1 = t.add_resource(
    elasticloadbalancingv2.ListenerRule(
        "ListenerRule1",
        Actions=[
            elasticloadbalancingv2.Action(TargetGroupArn=Ref(target_group),
                                          Type="forward")
        ],
        Conditions=[
            elasticloadbalancingv2.Condition(Field="path-pattern",
                                             Values=[Ref(service_path)]),
            If(
                service_host_condition,
                elasticloadbalancingv2.Condition(Field="host-header",
                                                 Values=[Ref(service_host)]),
                Ref("AWS::NoValue"))
        ],
        # ListenerArn=Ref(app_lb_listener),
        ListenerArn=ImportValue(Sub("${AlbStack}-AlbPublicListener80")),
        Priority=Ref(listener_priority)))

listener_rule2 = t.add_resource(
    elasticloadbalancingv2.ListenerRule(
        "ListenerRule2",
        Condition=certificate_arn_condition,
        Actions=[
            elasticloadbalancingv2.Action(TargetGroupArn=Ref(target_group),
Esempio n. 18
0
        VpcId=myvpc,
    ))

Listener = template.add_resource(
    elb.Listener("Listener",
                 Port="80",
                 Protocol="HTTP",
                 LoadBalancerArn=Ref(FrontendAlb),
                 DefaultActions=[
                     elb.Action(Type="forward", TargetGroupArn=Ref(WebTargets))
                 ]))

template.add_resource(
    elb.ListenerRule(
        "ListenerRule",
        ListenerArn=Ref(Listener),
        Conditions=[elb.Condition(Field="path-pattern", Values=["/*"])],
        Actions=[elb.Action(Type="forward", TargetGroupArn=Ref(WebTargets))],
        Priority="1"))

lcf = template.add_resource(
    LaunchConfiguration(
        "lcf",
        AssociatePublicIpAddress=False,
        ImageId='ami-63d53204',
        InstanceType='t2.nano',
        KeyName='Demo',
        SecurityGroups=[Ref(instancesg)],
    ))

asg = template.add_resource(
    AutoScalingGroup(
Esempio n. 19
0
def generate_template(d):

    # Set template metadata
    t = Template()
    t.add_version("2010-09-09")
    t.set_description(d["cf_template_description"])

    aws_account_id = Ref("AWS::AccountId")
    aws_region = Ref("AWS::Region")

    # Task definition
    task_definition = t.add_resource(
        TaskDefinition(
            "TaskDefinition",
            Family=Join(
                "",
                [d["env"], "-", d["project_name"], "-", d["service_name"]]),
            RequiresCompatibilities=["FARGATE"],
            Cpu=d["container_cpu"],
            Memory=d["container_memory"],
            NetworkMode="awsvpc",
            ExecutionRoleArn=ImportValue(d["ecs_stack_name"] +
                                         "-ECSClusterRole"),
            ContainerDefinitions=[
                ContainerDefinition(
                    Name=Join("", [
                        d["env"], "-", d["project_name"], "-",
                        d["service_name"]
                    ]),
                    Image=Join(
                        "",
                        [
                            aws_account_id, ".dkr.ecr.", aws_region,
                            ".amazonaws.com/", d["env"], d["project_name"],
                            d["service_name"], ":latest"
                        ],
                    ),
                    Essential=True,
                    PortMappings=[
                        PortMapping(
                            ContainerPort=d["container_port"],
                            HostPort=d["container_port"],
                        )
                    ],
                    EntryPoint=["sh", "-c"],
                    Command=[d["container_command"]],
                    LogConfiguration=LogConfiguration(
                        LogDriver="awslogs",
                        Options={
                            "awslogs-region":
                            aws_region,
                            "awslogs-group":
                            Join("", [
                                d["env"], "-", d["project_name"], "-",
                                d["service_name"]
                            ]),
                            "awslogs-stream-prefix":
                            "ecs",
                            "awslogs-create-group":
                            "true"
                        }))
            ],
            Tags=Tags(d["tags"],
                      {"Name": d["project_name"] + "-task-definition"}),
        ))

    # ECR
    ecr = t.add_resource(
        Repository(
            "ECR",
            DependsOn="ListenerRule",
            RepositoryName=Join(
                "",
                [d["env"], "-", d["project_name"], "-", d["service_name"]]),
            Tags=Tags(d["tags"], {"Name": d["project_name"] + "-ecr"}),
        ))
    # Target group
    target_group = t.add_resource(
        elb.TargetGroup(
            "TargetGroup",
            Name=Join("", [d["env"], "-", d["service_name"]]),
            HealthCheckIntervalSeconds="30",
            HealthCheckProtocol="HTTP",
            HealthCheckPort=d["container_port"],
            HealthCheckTimeoutSeconds="10",
            HealthyThresholdCount="4",
            HealthCheckPath=d["tg_health_check_path"],
            Matcher=elb.Matcher(HttpCode="200-299"),
            Port=d["container_port"],
            Protocol="HTTP",
            TargetType="ip",
            UnhealthyThresholdCount="3",
            VpcId=ImportValue(d["network_stack_name"] + "-VPCId"),
            Tags=Tags(d["tags"], {"Name": d["project_name"] + "-ecr"}),
        ))
    # Listener rule
    t.add_resource(
        elb.ListenerRule(
            "ListenerRule",
            DependsOn="TargetGroup",
            ListenerArn=ImportValue(d["ecs_stack_name"] + "-ListenerArnHTTP"),
            Conditions=[
                elb.Condition(Field="path-pattern",
                              Values=[d["application_path_api"]])
            ],
            Actions=[
                elb.Action(Type="forward", TargetGroupArn=Ref(target_group))
            ],
            Priority="1",
        ))
    # ECS service
    ecs_service = t.add_resource(
        Service(
            "ECSService",
            ServiceName=Join(
                "",
                [d["env"], "-", d["project_name"], "-", d["service_name"]]),
            DependsOn="pipeline",
            DesiredCount=d["container_desired_tasks_count"],
            TaskDefinition=Ref(task_definition),
            LaunchType="FARGATE",
            NetworkConfiguration=NetworkConfiguration(
                AwsvpcConfiguration=AwsvpcConfiguration(
                    Subnets=[
                        ImportValue(d["network_stack_name"] +
                                    "-PrivateSubnetId1"),
                        ImportValue(d["network_stack_name"] +
                                    "-PrivateSubnetId2"),
                    ],
                    SecurityGroups=[
                        ImportValue(d["ecs_stack_name"] + "-ECSClusterSG")
                    ],
                )),
            LoadBalancers=([
                LoadBalancer(
                    ContainerName=Join(
                        "",
                        [
                            d["env"], "-", d["project_name"], "-",
                            d["service_name"]
                        ],
                    ),
                    ContainerPort=d["container_port"],
                    TargetGroupArn=Ref(target_group),
                )
            ]),
            Cluster=ImportValue(d["ecs_stack_name"] + "-ECSClusterName"),
            Tags=Tags(d["tags"], {"Name": d["project_name"] + "-ecs-service"}),
        ))
    # App Autoscaling target

    # App Autoscaling policy

    # Codebuild project
    codebuild = t.add_resource(
        Project(
            "codebuild",
            Name=Join(
                "",
                [d["env"], "-", d["project_name"], "-", d["service_name"]]),
            DependsOn="ECR",
            ServiceRole=ImportValue(d["ecs_stack_name"] +
                                    "-CodebuildDeveloperRole"),
            Artifacts=Artifacts(
                Name="Build",
                Location=d["artifact_store"],
                Type="S3",
            ),
            Description="Build a docker image and send it to ecr",
            Source=Source(
                BuildSpec="buildspec.yml",
                Type="S3",
                Location=d["artifact_store"] + "/" + d["artifact_name"],
            ),
            Environment=Environment(
                ComputeType="BUILD_GENERAL1_SMALL",
                Image="aws/codebuild/standard:4.0",
                PrivilegedMode=True,
                Type="LINUX_CONTAINER",
                EnvironmentVariables=[
                    EnvironmentVariable(
                        Name="AWS_DEFAULT_REGION",
                        Type="PLAINTEXT",
                        Value=aws_region,
                    ),
                    EnvironmentVariable(
                        Name="SERVICE_NAME",
                        Type="PLAINTEXT",
                        Value=Join(
                            "",
                            [
                                d["env"], "-", d["project_name"], "-",
                                d["service_name"]
                            ],
                        ),
                    ),
                    EnvironmentVariable(
                        Name="IMAGE_URI",
                        Type="PLAINTEXT",
                        Value=Join(
                            "",
                            [
                                aws_account_id,
                                ".dkr.ecr.",
                                aws_region,
                                ".amazonaws.com/",
                                d["env"],
                                "-",
                                d["project_name"],
                                "-",
                                d["service_name"],
                            ],
                        ),
                    ),
                ],
            ),
            Tags=Tags(d["tags"], {"Name": d["project_name"] + "-codebuild"}),
        ))

    # Codepipeline
    pipeline = t.add_resource(
        Pipeline(
            "pipeline",
            Name=Join(
                "",
                [d["env"], "-", d["project_name"], "-", d["service_name"]]),
            RoleArn=ImportValue(d["ecs_stack_name"] + "-CodePipelineRole"),
            Stages=[
                Stages(
                    Name="Source",
                    Actions=[
                        Actions(
                            Name="Source",
                            ActionTypeId=ActionTypeId(
                                Category="Source",
                                Owner="AWS",
                                Version="1",
                                Provider="S3",
                            ),
                            OutputArtifacts=[
                                OutputArtifacts(Name="source_artifact")
                            ],
                            Configuration={
                                "S3Bucket": d["artifact_store"],
                                "S3ObjectKey": d["artifact_name"],
                            },
                            RunOrder="1",
                        )
                    ],
                ),
                Stages(
                    Name="Build",
                    Actions=[
                        Actions(
                            Name="Build",
                            InputArtifacts=[
                                InputArtifacts(Name="source_artifact")
                            ],
                            OutputArtifacts=[
                                OutputArtifacts(Name="build_artifact")
                            ],
                            ActionTypeId=ActionTypeId(
                                Category="Build",
                                Owner="AWS",
                                Version="1",
                                Provider="CodeBuild",
                            ),
                            Configuration={"ProjectName": Ref(codebuild)},
                            RunOrder="1",
                        )
                    ],
                ),
                Stages(
                    Name="Deploy",
                    Actions=[
                        Actions(
                            Name="Deploy",
                            InputArtifacts=[
                                InputArtifacts(Name="build_artifact")
                            ],
                            ActionTypeId=ActionTypeId(
                                Category="Deploy",
                                Owner="AWS",
                                Version="1",
                                Provider="ECS",
                            ),
                            Configuration={
                                "ClusterName":
                                ImportValue(d["ecs_stack_name"] +
                                            "-ECSClusterName"),
                                "ServiceName":
                                Join(
                                    "",
                                    [
                                        d["env"],
                                        "-",
                                        d["project_name"],
                                        "-",
                                        d["service_name"],
                                    ],
                                ),
                                "FileName":
                                "definitions.json",
                            },
                        )
                    ],
                ),
            ],
            ArtifactStore=ArtifactStore(Type="S3",
                                        Location=d["artifact_store"]),
        ))
    # Route53

    # Outputs

    return t
def main():
    # Meta
    t.add_version("2010-09-09")
    t.add_description("Template for auto-scaling in an Application"
                      "load balancer target group. "
                      "The ALB will be used as an A Alias target "
                      "for a specified Route53 hosted zone. "
                      "This template also showcases "
                      "Metadata Parameter Grouping, "
                      "Special AWS Parameter Types, "
                      "and Cloudformation Outputs with Exports"
                      "which can be imported into other templates.")
    t.add_metadata({
        "Author": "https://github.com/hmain/",
        "LastUpdated": "2017 01 31",
        "Version": "1",
    })

    # Parameter grouping
    t.add_metadata({
        "AWS::CloudFormation::Interface": {
            "ParameterGroups": [{
                "Label": {
                    "default": "Global parameters"
                },
                "Parameters": ["environment"]
            }, {
                "Label": {
                    "default": "Application Loadbalancer"
                },
                "Parameters": [
                    "albSubnets", "loadbalancerPrefix", "loadBalancerArn",
                    "albPaths", "albPort"
                ]
            }, {
                "Label": {
                    "default": "VPC"
                },
                "Parameters": ["ec2Subnets", "VPC", "securityGroup"]
            }, {
                "Label": {
                    "default": "EC2"
                },
                "Parameters": ["ec2Name", "ec2Type", "ec2Key"]
            }, {
                "Label": {
                    "default": "Auto-scaling"
                },
                "Parameters": [
                    "asgCapacity", "asgMinSize", "asgMaxSize", "asgCooldown",
                    "asgHealthGrace"
                ]
            }, {
                "Label": {
                    "default": "Route53"
                },
                "Parameters": ["route53HostedZoneId", "route53HostedZoneName"]
            }]
        }
    })

    AddAMI(t)

    environment = t.add_parameter(
        Parameter(
            "environment",
            Default="dev",
            Type="String",
            Description="Development or Production environment",
            AllowedValues=["dev", "prod"],
            ConstraintDescription="dev or prod",
        ))
    route53_hosted_zone_id = t.add_parameter(
        Parameter("route53HostedZoneId",
                  Default="",
                  Type="AWS::Route53::HostedZone::Id",
                  Description="Route53 DNS zone ID"))

    route53_hosted_zone_name = t.add_parameter(
        Parameter("route53HostedZoneName",
                  Default="my.aws.dns.com",
                  Type="String",
                  Description="Route53 hosted zone name"))
    security_group = t.add_parameter(
        Parameter("securityGroup",
                  Default="",
                  Type="List<AWS::EC2::SecurityGroup::Id>",
                  Description="Which security groups to use"))
    alb_paths = t.add_parameter(
        Parameter(
            "albPaths",
            Default="/",
            Type="CommaDelimitedList",
            Description="Path-patterns you want the loadbalancer to point to in "
            "your application"))
    albPort = t.add_parameter(
        Parameter("albPort",
                  Default="80",
                  Type="Number",
                  Description="Which loadbalancer port to use"))
    ec2_subnets = t.add_parameter(
        Parameter("ec2Subnets",
                  Default="",
                  Type="List<AWS::EC2::Subnet::Id>",
                  Description="Private subnets for the instances."))
    alb_subnets = t.add_parameter(
        Parameter("albSubnets",
                  Default="",
                  Type="List<AWS::EC2::Subnet::Id>",
                  Description="Public subnets for the load balancer."))
    loadbalancer_prefix = t.add_parameter(
        Parameter(
            "loadbalancerPrefix",
            Default="",
            Type="String",
            Description="Specify a prefix for your loadbalancer",
        ))
    vpc = t.add_parameter(
        Parameter("VPC",
                  Default="",
                  Type="AWS::EC2::VPC::Id",
                  Description="Environment VPC"))

    # Auto scaling group parameters
    asg_capacity = t.add_parameter(
        Parameter("asgCapacity",
                  Default="0",
                  Type="Number",
                  Description="Number of instances"))
    asg_min_size = t.add_parameter(
        Parameter("asgMinSize",
                  Default="0",
                  Type="Number",
                  Description="Minimum size of AutoScalingGroup"))
    asg_max_size = t.add_parameter(
        Parameter("asgMaxSize",
                  Default="1",
                  Type="Number",
                  Description="Maximum size of AutoScalingGroup"))
    asg_cooldown = t.add_parameter(
        Parameter(
            "asgCooldown",
            Default="300",
            Type="Number",
            Description="Cooldown before starting/stopping another instance"))
    asg_health_grace = t.add_parameter(
        Parameter(
            "asgHealthGrace",
            Default="300",
            Type="Number",
            Description="Wait before starting/stopping another instance"))

    # EC2 parameters
    ec2_name = t.add_parameter(
        Parameter("ec2Name",
                  Default="myApplication",
                  Type="String",
                  Description="Name of the instances"))
    ec2_type = t.add_parameter(
        Parameter("ec2Type",
                  Default="t2.large",
                  Type="String",
                  Description="Instance type."))
    ec2_key = t.add_parameter(
        Parameter("ec2Key",
                  Default="",
                  Type="AWS::EC2::KeyPair::KeyName",
                  Description="EC2 Key Pair"))

    # Launchconfiguration
    ec2_launchconfiguration = t.add_resource(
        autoscaling.LaunchConfiguration(
            "EC2LaunchConfiguration",
            ImageId=FindInMap("windowsAMI", Ref("AWS::Region"), "AMI"),
            KeyName=Ref(ec2_key),
            SecurityGroups=Ref(security_group),
            InstanceType=Ref(ec2_type),
            AssociatePublicIpAddress=False,
        ))

    # Application ELB
    alb_target_group = t.add_resource(
        elb.TargetGroup("albTargetGroup",
                        HealthCheckPath=Select("0", Ref(alb_paths)),
                        HealthCheckIntervalSeconds="30",
                        HealthCheckProtocol="HTTP",
                        HealthCheckTimeoutSeconds="10",
                        HealthyThresholdCount="4",
                        Matcher=elb.Matcher(HttpCode="200"),
                        Name=Ref(ec2_name),
                        Port=80,
                        Protocol="HTTP",
                        UnhealthyThresholdCount="3",
                        VpcId=Ref(vpc)))

    # Auto scaling group
    t.add_resource(
        autoscaling.AutoScalingGroup(
            "autoScalingGroup",
            DesiredCapacity=Ref(asg_capacity),
            Tags=autoscaling.Tags(Environment=Ref(environment)),
            VPCZoneIdentifier=Ref(ec2_subnets),
            TargetGroupARNs=[Ref(alb_target_group)],
            MinSize=Ref(asg_min_size),
            MaxSize=Ref(asg_max_size),
            Cooldown=Ref(asg_cooldown),
            LaunchConfigurationName=Ref(ec2_launchconfiguration),
            HealthCheckGracePeriod=Ref(asg_health_grace),
            HealthCheckType="EC2",
        ))

    # Application Load Balancer
    application_load_balancer = t.add_resource(
        elb.LoadBalancer("applicationLoadBalancer",
                         Name=Ref(loadbalancer_prefix),
                         Scheme="internet-facing",
                         Subnets=Ref(alb_subnets),
                         SecurityGroups=Ref(security_group)))
    alb_listener = t.add_resource(
        elb.Listener("albListener",
                     Port=Ref(albPort),
                     Protocol="HTTP",
                     LoadBalancerArn=Ref(application_load_balancer),
                     DefaultActions=[
                         elb.Action(Type="forward",
                                    TargetGroupArn=Ref(alb_target_group))
                     ]))
    t.add_resource(
        elb.ListenerRule("albListenerRule",
                         ListenerArn=Ref(alb_listener),
                         Conditions=[
                             elb.Condition(Field="path-pattern",
                                           Values=Ref(alb_paths))
                         ],
                         Actions=[
                             elb.Action(Type="forward",
                                        TargetGroupArn=Ref(alb_target_group))
                         ],
                         Priority="1"))

    # Route53
    t.add_resource(
        route53.RecordSetGroup(
            "route53RoundRobin",
            HostedZoneId=Ref(route53_hosted_zone_id),
            RecordSets=[
                route53.RecordSet(
                    Weight=1,
                    SetIdentifier=Join(".", [
                        Ref(environment),
                        Ref(route53_hosted_zone_name), "ELB"
                    ]),
                    Name=Join(
                        ".", [Ref(environment),
                              Ref(route53_hosted_zone_name)]),
                    Type="A",
                    AliasTarget=route53.AliasTarget(
                        GetAtt(application_load_balancer,
                               "CanonicalHostedZoneID"),
                        GetAtt(application_load_balancer, "DNSName")))
            ]))

    t.add_output(
        Output(
            "URL",
            Description="URL of the website",
            Value=Join("", [
                "http://",
                GetAtt(application_load_balancer, "DNSName"),
                Select("0", Ref(alb_paths))
            ]),
            Export=Export(Sub("${AWS::StackName}-URL")),
        ))

    print(t.to_json())