Пример #1
0
 def ecs_network_config(self):
     if self.family.service_compute.launch_type == "EXTERNAL":
         return NoValue
     return use_external_lt_con(
         NoValue,
         NetworkConfiguration(AwsvpcConfiguration=AwsvpcConfiguration(
             Subnets=self.subnets,
             SecurityGroups=self.security_groups,
             AssignPublicIp=self.eip_assign,
         )),
     )
Пример #2
0
        Description='A VPC subnet ID for the container.',
    ))

cluster = t.add_resource(Cluster('Cluster'))

task_definition = t.add_resource(
    TaskDefinition('TaskDefinition',
                   RequiresCompatibilities=['FARGATE'],
                   Cpu='256',
                   Memory='512',
                   NetworkMode='awsvpc',
                   ContainerDefinitions=[
                       ContainerDefinition(
                           Name='nginx',
                           Image='nginx',
                           Essential=True,
                           PortMappings=[PortMapping(ContainerPort=80)])
                   ]))

service = t.add_resource(
    Service(
        'NginxService',
        Cluster=Ref(cluster),
        DesiredCount=1,
        TaskDefinition=Ref(task_definition),
        LaunchType='FARGATE',
        NetworkConfiguration=NetworkConfiguration(
            AwsvpcConfiguration=AwsvpcConfiguration(Subnets=[Ref('Subnet')]))))

print(t.to_json())
    def _add_service(self, service_name, config):
        launch_type = self.LAUNCH_TYPE_FARGATE if 'fargate' in config else self.LAUNCH_TYPE_EC2
        env_config = build_config(
            self.env,
            self.application_name,
            self.env_sample_file_path
        )
        container_definition_arguments = {
            "Environment": [
                Environment(Name=k, Value=v) for (k, v) in env_config
            ],
            "Name": service_name + "Container",
            "Image": self.ecr_image_uri + ':' + self.current_version,
            "Essential": 'true',
            "LogConfiguration": self._gen_log_config(service_name),
            "MemoryReservation": int(config['memory_reservation']),
            "Cpu": 0
        }

        if 'http_interface' in config:
            container_definition_arguments['PortMappings'] = [
                PortMapping(
                    ContainerPort=int(
                        config['http_interface']['container_port']
                    )
                )
            ]

        if config['command'] is not None:
            container_definition_arguments['Command'] = [config['command']]

        cd = ContainerDefinition(**container_definition_arguments)

        task_role = self.template.add_resource(Role(
            service_name + "Role",
            AssumeRolePolicyDocument=PolicyDocument(
                Statement=[
                    Statement(
                        Effect=Allow,
                        Action=[AssumeRole],
                        Principal=Principal("Service", ["ecs-tasks.amazonaws.com"])
                    )
                ]
            )
        ))

        launch_type_td = {}
        if launch_type == self.LAUNCH_TYPE_FARGATE:
            launch_type_td = {
                'RequiresCompatibilities': ['FARGATE'],
                'ExecutionRoleArn': boto3.resource('iam').Role('ecsTaskExecutionRole').arn,
                'NetworkMode': 'awsvpc',
                'Cpu': str(config['fargate']['cpu']),
                'Memory': str(config['fargate']['memory'])
            }

        td = TaskDefinition(
            service_name + "TaskDefinition",
            Family=service_name + "Family",
            ContainerDefinitions=[cd],
            TaskRoleArn=Ref(task_role),
            **launch_type_td
        )

        self.template.add_resource(td)
        desired_count = self._get_desired_task_count_for_service(service_name)
        deployment_configuration = DeploymentConfiguration(
            MinimumHealthyPercent=100,
            MaximumPercent=200
        )
        if 'http_interface' in config:
            alb, lb, service_listener, alb_sg = self._add_alb(cd, service_name, config, launch_type)

            if launch_type == self.LAUNCH_TYPE_FARGATE:
                # if launch type is ec2, then services inherit the ec2 instance security group
                # otherwise, we need to specify a security group for the service
                service_security_group = SecurityGroup(
                    pascalcase("FargateService" + self.env + service_name),
                    GroupName=pascalcase("FargateService" + self.env + service_name),
                    SecurityGroupIngress=[{
                        'IpProtocol': 'TCP',
                        'SourceSecurityGroupId': Ref(alb_sg),
                        'ToPort': int(config['http_interface']['container_port']),
                        'FromPort': int(config['http_interface']['container_port']),
                    }],
                    VpcId=Ref(self.vpc),
                    GroupDescription=pascalcase("FargateService" + self.env + service_name)
                )
                self.template.add_resource(service_security_group)

                launch_type_svc = {
                    'NetworkConfiguration': NetworkConfiguration(
                        AwsvpcConfiguration=AwsvpcConfiguration(
                            Subnets=[
                                Ref(self.private_subnet1),
                                Ref(self.private_subnet2)
                            ],
                            SecurityGroups=[
                                Ref(service_security_group)
                            ]
                        )
                    )
                }
            else:
                launch_type_svc = {
                    'Role': Ref(self.ecs_service_role),
                    'PlacementStrategies': self.PLACEMENT_STRATEGIES
                }
            svc = Service(
                service_name,
                LoadBalancers=[lb],
                Cluster=self.cluster_name,
                TaskDefinition=Ref(td),
                DesiredCount=desired_count,
                DependsOn=service_listener.title,
                LaunchType=launch_type,
                **launch_type_svc,
            )
            self.template.add_output(
                Output(
                    service_name + 'EcsServiceName',
                    Description='The ECS name which needs to be entered',
                    Value=GetAtt(svc, 'Name')
                )
            )
            self.template.add_output(
                Output(
                    service_name + "URL",
                    Description="The URL at which the service is accessible",
                    Value=Sub("https://${" + alb.name + ".DNSName}")
                )
            )
            self.template.add_resource(svc)
        else:
            launch_type_svc = {}
            if launch_type == self.LAUNCH_TYPE_FARGATE:
                # if launch type is ec2, then services inherit the ec2 instance security group
                # otherwise, we need to specify a security group for the service
                service_security_group = SecurityGroup(
                    pascalcase("FargateService" + self.env + service_name),
                    GroupName=pascalcase("FargateService" + self.env + service_name),
                    SecurityGroupIngress=[],
                    VpcId=Ref(self.vpc),
                    GroupDescription=pascalcase("FargateService" + self.env + service_name)
                )
                self.template.add_resource(service_security_group)
                launch_type_svc = {
                    'NetworkConfiguration': NetworkConfiguration(
                        AwsvpcConfiguration=AwsvpcConfiguration(
                            Subnets=[
                                Ref(self.private_subnet1),
                                Ref(self.private_subnet2)
                            ],
                            SecurityGroups=[
                                Ref(service_security_group)
                            ]
                        )
                    )
                }
            else:
                launch_type_svc = {
                    'PlacementStrategies': self.PLACEMENT_STRATEGIES
                }
            svc = Service(
                service_name,
                Cluster=self.cluster_name,
                TaskDefinition=Ref(td),
                DesiredCount=desired_count,
                DeploymentConfiguration=deployment_configuration,
                LaunchType=launch_type,
                **launch_type_svc
            )
            self.template.add_output(
                Output(
                    service_name + 'EcsServiceName',
                    Description='The ECS name which needs to be entered',
                    Value=GetAtt(svc, 'Name')
                )
            )
            self.template.add_resource(svc)
        self._add_service_alarms(svc)
Пример #4
0
task_definition = t.add_resource(
    TaskDefinition(
        "TaskDefinition",
        RequiresCompatibilities=["FARGATE"],
        Cpu="256",
        Memory="512",
        NetworkMode="awsvpc",
        ContainerDefinitions=[
            ContainerDefinition(
                Name="nginx",
                Image="nginx",
                Essential=True,
                PortMappings=[PortMapping(ContainerPort=80)],
            )
        ],
    ))

service = t.add_resource(
    Service(
        "NginxService",
        Cluster=Ref(cluster),
        DesiredCount=1,
        TaskDefinition=Ref(task_definition),
        LaunchType="FARGATE",
        NetworkConfiguration=NetworkConfiguration(
            AwsvpcConfiguration=AwsvpcConfiguration(Subnets=[Ref("Subnet")])),
    ))

print(t.to_json())
Пример #5
0
def __create_ecs():
    template = Template()

    desired_count = template.add_parameter(
        parameter=Parameter(title='DesiredCount', Default=1, Type='Number'))

    cpu = template.add_parameter(
        parameter=Parameter(title='Cpu', Default=256, Type='Number'))

    memory = template.add_parameter(
        parameter=Parameter(title='Memory', Default=512, Type='Number'))

    cluster = template.add_resource(resource=Cluster(title='SampleCluster', ))

    log_group = template.add_resource(resource=LogGroup(
        title='SampleLogGroup', LogGroupName='/aws/ecs/sample'))

    container_name = 'sample-nginx'

    task_definition = template.add_resource(resource=TaskDefinition(
        title='SampleTaskDefinition',
        Cpu=Ref(cpu),
        Family='sample-fargate-task',
        RequiresCompatibilities=['FARGATE'],
        Memory=Ref(memory),
        NetworkMode='awsvpc',
        ExecutionRoleArn=Sub(
            'arn:aws:iam::${AWS::AccountId}:role/ecsTaskExecutionRole'),
        ContainerDefinitions=[
            ContainerDefinition(
                Image='nginx:latest',
                Name=container_name,
                PortMappings=[
                    PortMapping(ContainerPort=80, HostPort=80, Protocol='tcp')
                ],
                LogConfiguration=LogConfiguration(
                    LogDriver='awslogs',
                    Options={
                        'awslogs-region': Ref('AWS::Region'),
                        'awslogs-group': Ref(log_group),
                        'awslogs-stream-prefix': 'nginx'
                    }))
        ]))

    template.add_resource(resource=Service(
        title='SampleService',
        ServiceName='sample-fargate',
        Cluster=Ref(cluster),
        DesiredCount=Ref(desired_count),
        TaskDefinition=Ref(task_definition),
        LaunchType='FARGATE',
        NetworkConfiguration=NetworkConfiguration(
            AwsvpcConfiguration=AwsvpcConfiguration(
                AssignPublicIp='ENABLED',
                SecurityGroups=[
                    ImportValue(ExportName.TASK_SECURITY_GROUP.value)
                ],
                Subnets=[
                    ImportValue(
                        CommonResource.ExportName.PUBLIC_SUBNET_A_ID.value),
                    ImportValue(
                        CommonResource.ExportName.PUBLIC_SUBNET_B_ID.value),
                ])),
        LoadBalancers=[
            EcsLoadBalancer(ContainerName=container_name,
                            ContainerPort=80,
                            TargetGroupArn=ImportValue(
                                ExportName.TARGET_GROUP.value))
        ]))
    output_template_file(template, 'ecs.yml')
Пример #6
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
    Service('GhostService',
            Cluster=Ref(cluster),
            DesiredCount=1,
            TaskDefinition=Ref(ghost_task_definition),
            LaunchType='FARGATE',
            LoadBalancers=[
                LoadBalancer(ContainerName='ghost',
                             ContainerPort=2368,
                             TargetGroupArn=ImportValue(
                                 Sub("${DependencyStackName}-GhostTG")))
            ],
            NetworkConfiguration=NetworkConfiguration(
                AwsvpcConfiguration=AwsvpcConfiguration(
                    Subnets=[
                        ImportValue(Sub("${DependencyStackName}-Subnet1")),
                        ImportValue(Sub("${DependencyStackName}-Subnet2"))
                    ],
                    SecurityGroups=[
                        ImportValue(Sub("${DependencyStackName}-GhostSG"))
                    ],
                ))))

# Create the required Outputs

# Output the Fargate Service Name
t.add_output(
    Output("GhostFargateServiceName",
           Value=GetAtt(ghost_service, "Name"),
           Description="Ghost Fargate Service Name"))

print(t.to_json())
Пример #8
0
 def generate_service_definition(self, task_definition):
     """
     Function to generate the Service definition.
     This is the last step in defining the service, after all other settings have been prepared.
     """
     service_sgs = [
         Ref(sg) for sg in self.sgs
         if not isinstance(sg, (Ref, Sub, If, GetAtt))
     ]
     service_sgs += [
         sg for sg in self.sgs if isinstance(sg, (Ref, Sub, If, GetAtt))
     ]
     if self.config.replicas != ecs_params.SERVICE_COUNT.Default:
         self.parameters[ecs_params.SERVICE_COUNT_T] = self.config.replicas
     self.ecs_service = EcsService(
         ecs_params.SERVICE_T,
         template=self.template,
         Cluster=Ref(ecs_params.CLUSTER_NAME),
         DeploymentController=DeploymentController(
             Type=Ref(ecs_params.ECS_CONTROLLER)),
         EnableECSManagedTags=True,
         DesiredCount=If(
             ecs_conditions.SERVICE_COUNT_ZERO_AND_FARGATE_CON_T,
             1,
             If(
                 ecs_conditions.USE_FARGATE_CON_T,
                 Ref(ecs_params.SERVICE_COUNT),
                 If(
                     ecs_conditions.SERVICE_COUNT_ZERO_CON_T,
                     Ref(AWS_NO_VALUE),
                     Ref(ecs_params.SERVICE_COUNT),
                 ),
             ),
         ),
         SchedulingStrategy=If(
             ecs_conditions.USE_FARGATE_CON_T,
             "REPLICA",
             If(
                 ecs_conditions.SERVICE_COUNT_ZERO_AND_FARGATE_CON_T,
                 "REPLICA",
                 "DAEMON",
             ),
         ),
         HealthCheckGracePeriodSeconds=Ref(AWS_NO_VALUE),
         PlacementStrategies=If(
             ecs_conditions.USE_FARGATE_CON_T,
             Ref(AWS_NO_VALUE),
             define_placement_strategies(),
         ),
         NetworkConfiguration=NetworkConfiguration(
             AwsvpcConfiguration=AwsvpcConfiguration(
                 Subnets=Ref(vpc_params.APP_SUBNETS),
                 SecurityGroups=service_sgs)),
         TaskDefinition=Ref(task_definition),
         LaunchType=If(
             ecs_conditions.USE_CLUSTER_CAPACITY_PROVIDERS_CON_T,
             Ref(AWS_NO_VALUE),
             Ref(ecs_params.LAUNCH_TYPE),
         ),
         Tags=Tags({
             "Name": Ref(ecs_params.SERVICE_NAME),
             "StackName": Ref(AWS_STACK_NAME),
         }),
         PropagateTags="SERVICE",
         **self.service_attrs,
     )
Пример #9
0
def main():
    template = Template()
    template.add_version("2010-09-09")

    template.set_description("AWS CloudFormation ECS Service")

    # Add the Parameters

    Application = template.add_parameter(
        Parameter(
            "Application",
            Type="String",
        ))

    DockerImage = template.add_parameter(
        Parameter(
            "DockerImage",
            Type="String",
        ))

    ClusterName = template.add_parameter(
        Parameter(
            "ClusterName",
            Type="String",
        ))

    ContainerPort = template.add_parameter(
        Parameter(
            "ContainerPort",
            Type="String",
        ))

    HostPort = template.add_parameter(Parameter(
        "HostPort",
        Type="String",
    ))

    HostedZoneName = template.add_parameter(
        Parameter(
            "HostedZoneName",
            Type="String",
        ))

    CertArn = template.add_parameter(Parameter(
        "CertArn",
        Type="String",
    ))

    ExecutionRoleArn = template.add_parameter(
        Parameter("ExecutionRoleArn",
                  Type="String",
                  Description="Execution Role to get creadentials from ssm"))

    HealthCheckPath = template.add_parameter(
        Parameter(
            "HealthCheckPath",
            Type="String",
        ))

    HealthCheckIntervalSeconds = template.add_parameter(
        Parameter(
            "HealthCheckIntervalSeconds",
            Type="String",
        ))

    HealthyThresholdCount = template.add_parameter(
        Parameter(
            "HealthyThresholdCount",
            Type="String",
        ))

    HealthCheckTimeoutSeconds = template.add_parameter(
        Parameter(
            "HealthCheckTimeoutSeconds",
            Type="String",
        ))

    UnhealthyThresholdCount = template.add_parameter(
        Parameter(
            "UnhealthyThresholdCount",
            Type="String",
        ))

    VpcId = template.add_parameter(Parameter(
        "VpcId",
        Type="String",
    ))

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

    PrivateSubnets = template.add_parameter(
        Parameter(
            "PrivateSubnets",
            Type="List<AWS::EC2::Subnet::Id>",
        ))

    # Add the application ELB

    NetworkLB = template.add_resource(
        elb.LoadBalancer("NetworkLB",
                         Name=Join("", [Ref(Application), "-nlb"]),
                         Scheme="internet-facing",
                         Subnets=Ref(Subnets),
                         Type='network'))

    NlbTargetGroup = template.add_resource(
        elb.TargetGroup(
            "NlbTargetGroup",
            Name='ecs-fargate-service-targetgroup',
            HealthCheckIntervalSeconds=Ref(HealthCheckIntervalSeconds),
            HealthCheckProtocol="TCP",
            HealthyThresholdCount=Ref(HealthyThresholdCount),
            Port=80,
            Protocol="TCP",
            TargetType="ip",
            UnhealthyThresholdCount=Ref(UnhealthyThresholdCount),
            VpcId=Ref(VpcId)))

    NlbListener = template.add_resource(
        elb.Listener(
            "Listener",
            DependsOn=["NlbTargetGroup", "NetworkLB"],
            Certificates=[elb.Certificate(CertificateArn=Ref(CertArn))],
            Port="443",
            Protocol="TLS",
            LoadBalancerArn=Ref(NetworkLB),
            DefaultActions=[
                elb.Action(Type="forward", TargetGroupArn=Ref(NlbTargetGroup))
            ]))

    Task_Definition = template.add_resource(
        TaskDefinition(
            'TaskDefinition',
            Memory='512',
            Cpu='256',
            RequiresCompatibilities=['FARGATE'],
            NetworkMode='awsvpc',
            ExecutionRoleArn=Ref(ExecutionRoleArn),
            ContainerDefinitions=[
                ContainerDefinition(
                    Name=Join("", [Ref(Application)]),
                    Image=Ref(DockerImage),
                    Essential=True,
                    Environment=[Environment(Name="MY_ENV_VAR", Value="true")],
                    DockerLabels={
                        'aws-account': Ref("AWS::AccountId"),
                        'region': Ref("AWS::Region"),
                        'stack': Ref("AWS::StackName")
                    },
                    PortMappings=[
                        PortMapping(ContainerPort=Ref(ContainerPort))
                    ])
            ]))

    AwsVpcSg = template.add_resource(
        ec2.SecurityGroup('SecurityGroup',
                          GroupDescription='Security Group',
                          SecurityGroupIngress=[
                              ec2.SecurityGroupRule(IpProtocol='-1',
                                                    CidrIp='10.0.0.0/8')
                          ],
                          SecurityGroupEgress=[
                              ec2.SecurityGroupRule(IpProtocol="-1",
                                                    CidrIp="0.0.0.0/0")
                          ],
                          VpcId=Ref(VpcId)))

    app_service = template.add_resource(
        Service("AppService",
                DependsOn=["Listener", "TaskDefinition"],
                Cluster=Ref(ClusterName),
                LaunchType='FARGATE',
                DesiredCount=1,
                TaskDefinition=Ref(Task_Definition),
                ServiceName=Join("", [Ref(Application), "-ecs-service"]),
                LoadBalancers=[
                    ecs.LoadBalancer(ContainerName=Join(
                        "", [Ref(Application)]),
                                     ContainerPort=Ref(ContainerPort),
                                     TargetGroupArn=Ref(NlbTargetGroup))
                ],
                NetworkConfiguration=NetworkConfiguration(
                    AwsvpcConfiguration=AwsvpcConfiguration(
                        Subnets=Ref(PrivateSubnets),
                        SecurityGroups=[Ref(AwsVpcSg)]))))

    AppDNSRecord = template.add_resource(
        RecordSetType(
            "AppDNSRecord",
            DependsOn=["AppService"],
            HostedZoneName=Join("", [Ref(HostedZoneName), "."]),
            Name=Join("", [Ref(Application), ".",
                           Ref(HostedZoneName), "."]),
            Type="CNAME",
            TTL="900",
            ResourceRecords=[GetAtt(NetworkLB, "DNSName")]))

    template.add_output(
        Output("URL",
               Description="DomainName",
               Value=Join("", ["https://", Ref(AppDNSRecord)])))

    with open("ecs-fargate-service-cf.yaml", "w") as yamlout:
        yamlout.write(template.to_yaml())
Пример #10
0
        DesiredCount=1,
        HealthCheckGracePeriodSeconds=300,
        LaunchType="FARGATE",
        LoadBalancers=[
            LoadBalancer(
                "HelloWorldECSServiceLB",
                ContainerName="hello-world-web",
                ContainerPort=80,
                TargetGroupArn=Ref(resources["ALBTargetGroup"]),
            )
        ],
        NetworkConfiguration=NetworkConfiguration(
            "HelloWorldNetConf",
            AwsvpcConfiguration=AwsvpcConfiguration(
                "HelloWorldVPCConf",
                AssignPublicIp="DISABLED",
                SecurityGroups=[
                    Ref(resources["HelloWorldECSTaskSecurityGroup"])
                ],
                Subnets=[ImportValue("PRVA"),
                         ImportValue("PRVB")])),
        ServiceName=Join("-", [Ref(parameters["Project"]), "ecs", "service"]),
        TaskDefinition=Ref(resources["HelloWorldTaskDef"])))

### Template JSON ###

output = open(
    path.dirname(path.abspath(__file__)) + "/" +
    path.splitext(path.basename(__file__))[0] + ".json", "w")
#print(template.to_json())
output.write(template.to_json())
output.close()