Ejemplo n.º 1
0
    def gen_task_definition(self):
        log_configuration = ecs.LogConfiguration(
            LogDriver="awslogs",
            Options={
                "awslogs-group": self.log_group_name,
                "awslogs-region": Ref("AWS::Region"),
                "awslogs-stream-prefix": self.service_name,
            },
        )

        container_definition = ecs.ContainerDefinition(
            Name=self.service_name,
            Image=self.get_service_image(),
            PortMappings=[ecs.PortMapping(ContainerPort=80, Protocol="tcp")],
            LogConfiguration=log_configuration,
            Essential=True,
        )

        self.task_definition = ecs.TaskDefinition(
            "TasDefinition",
            Family="conducto-demo-family",
            ExecutionRoleArn=Ref(self.execution_role),
            TaskRoleArn=Ref(self.task_role),
            NetworkMode="awsvpc",
            RequiresCompatibilities=["FARGATE"],
            Cpu=f"0.25 vCPU",
            Memory="0.5 GB",
            ContainerDefinitions=[container_definition],
        )
        self.template.add_resource(self.task_definition)
Ejemplo n.º 2
0
 def container_port_mappings(self):
     mappings = NoValue
     if self.container_port:
         kwargs = {"ContainerPort": self.container_port}
         if self.host_port:
             kwargs["HostPort"] = self.host_port
         if self.container_protocol:
             kwargs["Protocol"] = self.container_protocol
         mappings = [ecs.PortMapping(**kwargs)]
     return mappings
Ejemplo n.º 3
0
    def test_allow_port_mapping_protocol(self):
        container_definition = ecs.ContainerDefinition(
            Image="myimage",
            Memory="300",
            Name="mycontainer",
            PortMappings=[
                ecs.PortMapping(ContainerPort=8125, HostPort=8125, Protocol="udp")
            ],
        )

        container_definition.to_dict()
Ejemplo n.º 4
0
    def test_port_mapping_does_not_require_protocol(self):
        container_definition = ecs.ContainerDefinition(
            Image="myimage",
            Memory="300",
            Name="mycontainer",
            PortMappings=[
                ecs.PortMapping(
                    ContainerPort=8125,
                    HostPort=8125,
                )
            ])

        container_definition.JSONrepr()
Ejemplo n.º 5
0
 def create_task_definition(self, t):
     return t.add_resource(ecs.TaskDefinition(
         self.resource_name_format % ('TaskDefinition'),
         Family=Sub('${AWS::StackName}-app'),
         ContainerDefinitions=[ecs.ContainerDefinition(
             Name=self.container_name,
             Image=self.docker_image,
             Memory=self.memory,
             PortMappings=[ecs.PortMapping(ContainerPort=self.port)],
             Environment=[
                 ecs.Environment(Name=key, Value=value)
                 for (key, value) in sorted(self.get_envs(t).items())
             ]
         )]
     ))
Ejemplo n.º 6
0
    def add_ecs(self, name, image, cpu, memory, container_port, alb_port,
                envvars, cidr, hosted_zone):
        """
        Helper method creates ingress given a source cidr range and a set of
        ports
        @param name [string] Name of the service
        @param image [string] Docker image name
        @param memory [int] Sets the memory size of the service
        @param envvars [list] List of envvars
        @param cidr [string] Range of addresses for this vpc
        @param hosted_zone [string] Name of the hosted zone the elb will be
        mapped to
        """
        print "Creating ECS"

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

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

        container_def = ecs.ContainerDefinition(
            name + 'containerdef',
            Name=name,
            Image=image,
            Cpu=cpu,
            Memory=memory,
            PortMappings=[ecs.PortMapping(ContainerPort=container_port)])

        task_def = self.add_resource(
            ecs.TaskDefinition(name + 'taskdef',
                               Cpu=cpu,
                               Memory=memory,
                               RequiresCompatibilities=['FARGATE'],
                               NetworkMode='awsvpc',
                               ContainerDefinitions=[container_def]))

        self.add_resource(
            ecs.Service(name + 'service',
                        Cluster=Ref(cluster),
                        LaunchType='FARGATE',
                        TaskDefinition=Ref(task_def),
                        DesiredCount=1))
Ejemplo n.º 7
0
def create_api_task_definition_resource(template, api_task_definition_family_variable, docker_repository_resource,
                                        api_log_group_resource):
    return template.add_resource(
        ecs.TaskDefinition(
            'ApiTaskDefinition',
            Family=api_task_definition_family_variable,
            NetworkMode='bridge',
            RequiresCompatibilities=['EC2'],
            ContainerDefinitions=[ecs.ContainerDefinition(
                Name='api',
                Image=Join('.', [
                    Ref('AWS::AccountId'),
                    'dkr.ecr',
                    Ref('AWS::Region'),
                    Join('/', [
                        'amazonaws.com',
                        Ref(docker_repository_resource)
                    ])
                ]),
                MemoryReservation='256',
                PortMappings=[ecs.PortMapping(
                    HostPort='0',
                    ContainerPort='80',
                    Protocol='tcp'
                )],
                Essential=True,
                LogConfiguration=ecs.LogConfiguration(
                    LogDriver='awslogs',
                    Options={
                        'awslogs-group': Ref(api_log_group_resource),
                        'awslogs-region': Ref('AWS::Region'),
                        'awslogs-stream-prefix': 'ecs'
                    }
                )
            )]
        )
    )
Ejemplo n.º 8
0
    def create_ecs_resources(self):
        t = self.template

        # Give the instances access that the Empire daemon needs.
        t.add_resource(
            PolicyType(
                "AccessPolicy",
                PolicyName="empire",
                PolicyDocument=empire_policy({
                    "Environment":
                    Ref("Environment"),
                    "CustomResourcesTopic":
                    Ref("CustomResourcesTopic"),
                    "CustomResourcesQueue": (GetAtt("CustomResourcesQueue",
                                                    "Arn")),
                    "TemplateBucket":
                    (Join("", ["arn:aws:s3:::",
                               Ref("TemplateBucket"), "/*"]))
                }),
                Roles=[Ref("InstanceRole")]))

        t.add_resource(
            sns.Topic(
                EVENTS_TOPIC,
                DisplayName="Empire events",
                Condition="CreateSNSTopic",
            ))
        t.add_output(
            Output("EventsSNSTopic",
                   Value=Ref(EVENTS_TOPIC),
                   Condition="CreateSNSTopic"))

        # Add SNS Events policy if Events are enabled
        t.add_resource(
            PolicyType("SNSEventsPolicy",
                       PolicyName="EmpireSNSEventsPolicy",
                       Condition="EnableSNSEvents",
                       PolicyDocument=sns_events_policy(
                           If("CreateSNSTopic", Ref(EVENTS_TOPIC),
                              Ref("EventsSNSTopicName"))),
                       Roles=[Ref("InstanceRole")]))

        # Add run logs policy if run logs are enabled
        t.add_resource(
            PolicyType("RunLogsPolicy",
                       PolicyName="EmpireRunLogsPolicy",
                       Condition="EnableCloudwatchLogs",
                       PolicyDocument=runlogs_policy(
                           If("CreateRunLogsGroup", Ref(RUN_LOGS),
                              Ref("RunLogsCloudwatchGroup"))),
                       Roles=[Ref("InstanceRole")]))

        # Allow the controller to write empire events to kinesis if kinesis is
        # enabled.
        t.add_resource(
            PolicyType("AppEventStreamPolicy",
                       PolicyName="EmpireAppEventStreamPolicy",
                       Condition="EnableAppEventStream",
                       PolicyDocument=logstream_policy(),
                       Roles=[Ref("InstanceRole")]))

        t.add_resource(
            ecs.TaskDefinition(
                "TaskDefinition",
                Volumes=[
                    ecs.Volume(
                        Name="dockerSocket",
                        Host=ecs.Host(SourcePath="/var/run/docker.sock")),
                    ecs.Volume(Name="dockerCfg",
                               Host=ecs.Host(SourcePath="/root/.dockercfg"))
                ],
                ContainerDefinitions=[
                    ecs.ContainerDefinition(
                        Command=["server", "-automigrate=true"],
                        Name="empire",
                        Environment=self.get_empire_environment(),
                        Essential=True,
                        Image=Ref("DockerImage"),
                        MountPoints=[
                            ecs.MountPoint(
                                SourceVolume="dockerSocket",
                                ContainerPath="/var/run/docker.sock",
                                ReadOnly=False),
                            ecs.MountPoint(SourceVolume="dockerCfg",
                                           ContainerPath="/root/.dockercfg",
                                           ReadOnly=False)
                        ],
                        PortMappings=[
                            ecs.PortMapping(HostPort=8081, ContainerPort=8081)
                        ],
                        Cpu=Ref("TaskCPU"),
                        Memory=Ref("TaskMemory"))
                ]))

        t.add_resource(
            Role("ServiceRole",
                 AssumeRolePolicyDocument=get_ecs_assumerole_policy(),
                 Path="/",
                 Policies=[
                     Policy(PolicyName="ecs-service-role",
                            PolicyDocument=service_role_policy())
                 ]))

        t.add_resource(
            ecs.Service(
                "Service",
                Cluster=Ref("ControllerCluster"),
                DeploymentConfiguration=ecs.DeploymentConfiguration(
                    MaximumPercent=Ref("ServiceMaximumPercent"),
                    MinimumHealthyPercent=Ref("ServiceMinimumHealthyPercent"),
                ),
                DesiredCount=Ref("DesiredCount"),
                LoadBalancers=[
                    ecs.LoadBalancer(ContainerName="empire",
                                     ContainerPort=8081,
                                     LoadBalancerName=Ref("LoadBalancer"))
                ],
                Role=Ref("ServiceRole"),
                TaskDefinition=Ref("TaskDefinition")))
Ejemplo n.º 9
0
def main():
    template = Template()

    template.add_resource(
        ecs.Cluster("ECSCluster", ClusterName="WorldCheckCluster"))

    template.add_resource(
        iam.Role("ECSTaskRole",
                 AssumeRolePolicyDocument={
                     "Version":
                     "2012-10-17",
                     "Statement": [{
                         "Effect": "Allow",
                         "Principal": {
                             "Service": ["ecs-tasks.amazonaws.com"]
                         },
                         "Action": ["sts:AssumeRole"]
                     }]
                 }))

    template.add_resource(
        iam.Role(
            "ECSServiceSchedulerRole",
            AssumeRolePolicyDocument={
                "Version":
                "2012-10-17",
                "Statement": [{
                    "Effect": "Allow",
                    "Principal": {
                        "Service": ["ecs.amazonaws.com"]
                    },
                    "Action": ["sts:AssumeRole"]
                }]
            },
            Policies=[
                iam.Policy(PolicyDocument={
                    "Version":
                    "2012-10-17",
                    "Statement": [{
                        "Effect":
                        "Allow",
                        "Action": [
                            "ec2:Describe*",
                            "elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
                            "elasticloadbalancing:DeregisterTargets",
                            "elasticloadbalancing:Describe*",
                            "elasticloadbalancing:RegisterInstancesWithLoadBalancer",
                            "elasticloadbalancing:RegisterTargets"
                        ],
                        "Resource":
                        "*"
                    }]
                },
                           PolicyName="ecs-service")
            ]))

    template.add_resource(
        iam.Role("EC2InstanceRole",
                 AssumeRolePolicyDocument={
                     "Version":
                     "2012-10-17",
                     "Statement": [{
                         "Effect": "Allow",
                         "Principal": {
                             "Service": ["ec2.amazonaws.com"]
                         },
                         "Action": ["sts:AssumeRole"]
                     }]
                 },
                 Policies=[
                     iam.Policy(PolicyDocument={
                         "Version":
                         "2012-10-17",
                         "Statement": [{
                             "Effect":
                             "Allow",
                             "Action": [
                                 "ecs:CreateCluster",
                                 "ecs:DeregisterContainerInstance",
                                 "ecs:DiscoverPollEndpoint", "ecs:Poll",
                                 "ecs:RegisterContainerInstance",
                                 "ecs:StartTelemetrySession",
                                 "ecr:GetAuthorizationToken",
                                 "ecr:BatchGetImage",
                                 "ecr:GetDownloadUrlForLayer", "ecs:Submit*",
                                 "logs:CreateLogStream", "logs:PutLogEvents",
                                 "ec2:DescribeTags", "cloudwatch:PutMetricData"
                             ],
                             "Resource":
                             "*"
                         }]
                     },
                                PolicyName="ecs-service")
                 ]))
    template.add_resource(
        iam.InstanceProfile("EC2InstanceProfile",
                            Roles=[Ref("EC2InstanceRole")]))

    with open("user-data.sh", "r") as f:
        user_data_content = f.readlines()

    template.add_resource(
        ec2.Instance(
            "EC2Instance",
            ImageId="ami-13f7226a",
            InstanceType="t2.micro",
            SecurityGroups=["default"],
            UserData=Base64(Join('', [Sub(x) for x in user_data_content])),
            IamInstanceProfile=Ref("EC2InstanceProfile"),
        ))

    template.add_resource(
        ecs.TaskDefinition(
            "ECSTaskDefinition",
            TaskRoleArn=Ref("ECSTaskRole"),
            ContainerDefinitions=[
                ecs.ContainerDefinition(
                    Name="SimpleServer",
                    Memory="128",
                    Image="abbas123456/simple-server:latest",
                    PortMappings=[ecs.PortMapping(ContainerPort=8000)],
                )
            ]))

    template.add_resource(
        elb.TargetGroup(
            "ECSTargetGroup",
            VpcId="vpc-925497f6",
            Port=8000,
            Protocol="HTTP",
        ))

    template.add_resource(
        elb.LoadBalancer(
            "LoadBalancer",
            Subnets=["subnet-a321c8fb", "subnet-68fa271e", "subnet-689d350c"],
            SecurityGroups=["sg-0202bd65"]))

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

    template.add_resource(
        ecs.Service("ECSService",
                    Cluster=Ref("ECSCluster"),
                    DesiredCount=1,
                    LoadBalancers=[
                        ecs.LoadBalancer(ContainerPort=8000,
                                         ContainerName="SimpleServer",
                                         TargetGroupArn=Ref("ECSTargetGroup"))
                    ],
                    Role=Ref("ECSServiceSchedulerRole"),
                    TaskDefinition=Ref("ECSTaskDefinition"),
                    DependsOn="LoadBalancerListener"))

    return template.to_json()
Ejemplo n.º 10
0
        RequiresCompatibilities=['EC2'],
        ContainerDefinitions=[ecs.ContainerDefinition(
            Name='api',
            Image=Join('.', [
                Ref('AWS::AccountId'),
                'dkr.ecr',
                Ref('AWS::Region'),
                Join('/', [
                    'amazonaws.com',
                    Ref(docker_repository)
                ])
            ]),
            MemoryReservation='256',
            PortMappings=[ecs.PortMapping(
                HostPort='0',
                ContainerPort='80',
                Protocol='tcp'
            )],
            Essential=True,
            LogConfiguration=ecs.LogConfiguration(
                LogDriver='awslogs',
                Options={
                    'awslogs-group': Ref(api_log_group),
                    'awslogs-region': Ref('AWS::Region'),
                    'awslogs-stream-prefix': 'ecs'
                }
            )
        )]
    )
)
Ejemplo n.º 11
0
    def add_resources(self):
        """Add resources to template."""
        class EcsServiceWithHealthCheckGracePeriodSeconds(ecs.Service):
            """ECS Service class with HealthCheckGracePeriodSeconds added."""

            props = ecs.Service.props
            props['HealthCheckGracePeriodSeconds'] = (positive_integer, False)

        pkg_version = pkg_resources.get_distribution('troposphere').version
        if LooseVersion(pkg_version) < LooseVersion('2.1.3'):
            ecs_service = EcsServiceWithHealthCheckGracePeriodSeconds
        else:
            ecs_service = ecs.Service

        template = self.template
        variables = self.get_variables()

        ecstaskrole = template.add_resource(
            iam.Role('EcsTaskRole',
                     AssumeRolePolicyDocument=get_ecs_task_assumerole_policy(),
                     RoleName=variables['EcsTaskRoleName'].ref))

        loggroup = template.add_resource(
            logs.LogGroup(
                'CloudWatchLogGroup',
                LogGroupName=Join('', [
                    '/ecs/', variables['ContainerName'].ref, '-',
                    variables['EnvironmentName'].ref
                ]),
                RetentionInDays=variables['EcsCloudWatchLogRetention'].ref))

        ecscontainerdef = ecs.ContainerDefinition(
            Image=Join('', [
                Ref('AWS::AccountId'), '.dkr.ecr.',
                Ref('AWS::Region'), '.amazonaws.com/',
                variables['ContainerName'].ref, '-',
                variables['EnvironmentName'].ref
            ]),
            LogConfiguration=ecs.LogConfiguration(LogDriver='awslogs',
                                                  Options={
                                                      'awslogs-group':
                                                      Ref(loggroup),
                                                      'awslogs-region':
                                                      Ref('AWS::Region'),
                                                      'awslogs-stream-prefix':
                                                      'ecs'
                                                  }),
            Name=Join('-', [
                variables['ContainerName'].ref,
                variables['EnvironmentName'].ref
            ]),
            PortMappings=[
                ecs.PortMapping(ContainerPort=variables['ContainerPort'].ref)
            ])

        ecstaskdef = template.add_resource(
            ecs.TaskDefinition(
                'EcsTaskDef',
                ContainerDefinitions=[ecscontainerdef],
                Cpu=variables['TaskCpu'].ref,
                Memory=variables['TaskMem'].ref,
                ExecutionRoleArn=variables['EcsTaskExecIamRoleArn'].ref,
                TaskRoleArn=Ref(ecstaskrole),
                Family=Join('-', [
                    variables['ContainerName'].ref,
                    variables['EnvironmentName'].ref
                ]),
                NetworkMode='awsvpc',
                RequiresCompatibilities=['FARGATE']))

        ecscluster = template.add_resource(
            ecs.Cluster('EcsCluster',
                        ClusterName=Join('-', [
                            variables['ContainerName'].ref,
                            variables['EnvironmentName'].ref
                        ])))

        ecsservice = template.add_resource(
            ecs_service(
                'EcsService',
                Cluster=Join('-', [
                    variables['ContainerName'].ref,
                    variables['EnvironmentName'].ref
                ]),
                DeploymentConfiguration=ecs.DeploymentConfiguration(
                    MinimumHealthyPercent=variables['MinHealthyPercent'].ref,
                    MaximumPercent=variables['MaxPercent'].ref),
                DesiredCount=variables['NumberOfTasks'].ref,
                HealthCheckGracePeriodSeconds=variables[
                    'HealthCheckGracePeriod'].ref,
                LaunchType='FARGATE',
                LoadBalancers=[
                    ecs.LoadBalancer(
                        ContainerName=Join('-', [
                            variables['ContainerName'].ref,
                            variables['EnvironmentName'].ref
                        ]),
                        ContainerPort=variables['ContainerPort'].ref,
                        TargetGroupArn=variables['TargetGroupArn'].ref)
                ],
                NetworkConfiguration=ecs.NetworkConfiguration(
                    AwsvpcConfiguration=ecs.AwsvpcConfiguration(
                        SecurityGroups=variables['SgIdList'].ref,
                        Subnets=variables['Subnets'].ref)),
                ServiceName=Join('-', [
                    variables['ContainerName'].ref,
                    variables['EnvironmentName'].ref
                ]),
                TaskDefinition=Ref(ecstaskdef)))

        template.add_output(
            Output("{}Arn".format(ecstaskrole.title),
                   Description="ECS Task Role ARN",
                   Value=GetAtt(ecstaskrole, "Arn"),
                   Export=Export(
                       Sub('${AWS::StackName}-%sArn' % ecstaskrole.title))))

        template.add_output(
            Output("{}Name".format(ecstaskrole.title),
                   Description="ECS Task Role Name",
                   Value=Ref(ecstaskrole)))

        template.add_output(
            Output("{}Arn".format(ecsservice.title),
                   Description="ARN of the ECS Service",
                   Value=Ref(ecsservice),
                   Export=Export(
                       Sub('${AWS::StackName}-%sArn' % ecsservice.title))))

        template.add_output(
            Output("{}Name".format(ecsservice.title),
                   Description="Name of the ECS Service",
                   Value=GetAtt(ecsservice, "Name"),
                   Export=Export(
                       Sub('${AWS::StackName}-%sName' % ecsservice.title))))

        template.add_output(
            Output("{}Arn".format(ecscluster.title),
                   Description="ECS Cluster ARN",
                   Value=GetAtt(ecscluster, "Arn"),
                   Export=Export(
                       Sub('${AWS::StackName}-%sArn' % ecscluster.title))))

        template.add_output(
            Output("{}Arn".format(ecstaskdef.title),
                   Description="ARN of the Task Definition",
                   Value=Ref(ecstaskdef),
                   Export=Export(
                       Sub('${AWS::StackName}-%sArn' % ecstaskdef.title))))
Ejemplo n.º 12
0
 TaskRoleArn=GetAtt(task_role, "Arn"),
 NetworkMode="bridge",
 Family=Ref(family),
 ContainerDefinitions=[
     ecs.ContainerDefinition(
         LogConfiguration=ecs.LogConfiguration(
             LogDriver="awslogs",
             Options={
                 "awslogs-group": Ref("AWS::StackName"),
                 "awslogs-region": Ref("AWS::Region"),
                 "awslogs-stream-prefix": Ref(container_name)
             }),
         Memory=2048,
         PortMappings=[
             ecs.PortMapping(HostPort=0,
                             ContainerPort=Ref(container_port),
                             Protocol="tcp"),
         ],
         Essential=True,
         Command=["/usr/sbin/apache2ctl", "-D", "FOREGROUND"],
         Name=Ref(container_name),
         Image=Join(
             "", [Ref(ecr), "/",
                  Ref(image_name), ":",
                  Ref(image_tag)]),
         Cpu=200,
         MemoryReservation=512,
         Environment=[
             ecs.Environment(Name="AWSStackName",
                             Value=Ref("AWS::StackName")),
             ecs.Environment(Name="AWSRegion",
Ejemplo n.º 13
0
 ecs.ContainerDefinition(
     Essential=True,
     Image=
     'xli9999/aws-currency-exchange-service-h2-xray:0.0.1-SNAPSHOT',
     LogConfiguration=ecs.LogConfiguration(
         LogDriver='awslogs',
         Options={
             "awslogs-group":
             '/ecs/aws-currency-exchange-service-h2-xray',
             "awslogs-region": 'us-east-2',
             "awslogs-stream-prefix": 'ecs'
         }),
     Name='aws-currency-exchange-service-h2-xray',
     PortMappings=[
         ecs.PortMapping(ContainerPort=8000,
                         HostPort=8000,
                         Protocol='tcp')
     ]),
 ecs.ContainerDefinition(
     Environment=[
         ecs.Environment(
             Name='APPMESH_VIRTUAL_NODE_NAME',
             Value=
             'mesh/my-service-mesh/virtualNode/currency-exchange-service-vn'
         ),
         ecs.Environment(Name='ENABLE_ENVOY_XRAY_TRACING',
                         Value='1'),
         ecs.Environment(Name='ENVOY_LOG_LEVEL', Value='trace')
     ],
     Essential=True,
     HealthCheck=ecs.HealthCheck(Command=[
Ejemplo n.º 14
0
    def __init__(self, title, key, index, **kwargs):
        super().__init__(title, **kwargs)

        name = self.title  # Ex. ContainerDefinitions1
        auto_get_props(self, key, recurse=True)

        self.Essential = True

        if len(cfg.ContainerDefinitions) == 1:
            self.Cpu = If(
                'CpuTask',
                get_endvalue('Cpu'),
                get_endvalue(f'{name}Cpu')
            )
            self.Memory = If(
                'LaunchTypeFarGate',
                get_endvalue('Memory'),
                get_endvalue(f'{name}Memory')
            )

        if 'RepoName' in key:
            self.Image = get_subvalue(
                '${1M}.dkr.ecr.${AWS::Region}.amazonaws.com/${2M}:'
                '${EnvApp%sVersion}' % index,
                ['EcrAccount', f'{name}RepoName']
            )
        # use the same EnvApp version for all containers
        elif cfg.RepoName != 'None':
            self.Image = get_subvalue(
                '${1M}.dkr.ecr.${AWS::Region}.amazonaws.com/${2M}:'
                '${EnvApp1Version}',
                ['EcrAccount', 'RepoName']
            )
        elif cfg.Image != 'None':
            self.Image = get_endvalue('Image')

        self.LogConfiguration = If(
            'LogConfiguration',
            ecs.LogConfiguration(
                LogDriver=get_endvalue('LogDriver'),
                Options={
                    # 'awslogs-group': get_endvalue('AwsLogsGroup'),
                    # 'awslogs-create-group': True,
                    'awslogs-group': Ref('LogsLogGroup'),
                    'awslogs-region': Ref('AWS::Region'),
                    'awslogs-stream-prefix': Ref('AWS::StackName')
                }
            ),
            Ref('AWS::NoValue')
        )

        if 'MountPoints' in key:
            self.MountPoints = [
                ECSMountPoint(n, key=k) for n, k in key['MountPoints'].items()
            ]

        if 'Name' in key:
            self.Name = get_subvalue('${EnvRole}-${1M}', f'{name}Name')
        else:
            self.Name = Ref('EnvRole')

        if 'ContainerPort' in key:
            PortMapping = ecs.PortMapping()
            auto_get_props(PortMapping, key, mapname=self.title)
            if 'HostPort' not in key:
                PortMapping.HostPort = If(
                    'NetworkModeAwsVpc',
                    get_endvalue(f'{name}ContainerPort'),
                    0
                )
            self.PortMappings = [PortMapping]
Ejemplo n.º 15
0
    def munge_container_attributes(self):
        image = ':'.join([
            self.vars['ContainerImage'],
            str(self.vars['ContainerImageVersion']),
        ])
        # munge ECR image path
        if self.vars['UseECR']:
            image = Join(
                '.', [AccountId, 'dkr.ecr', Region, 'amazonaws.com/' + image])
        # set required attributes
        required = dict(
            Name=self.vars['ContainerName'],
            Image=image,
            PortMappings=[
                ecs.PortMapping(
                    ContainerPort=self.vars['ContainerPort'],
                    Protocol=self.vars['ContainerProtocol'],
                )
            ],
            LogConfiguration=ecs.LogConfiguration(
                LogDriver='awslogs',
                Options={
                    'awslogs-group': Ref(self.log_group),
                    'awslogs-region': Region,
                    'awslogs-stream-prefix': self.vars['ContainerName'],
                },
            ),
        )
        # deal with additional attributes
        if self.vars['AdditionalContainerAttributes']:
            added = self.vars['AdditionalContainerAttributes']
            # deal with troposphere AWSProperty objects
            if 'Environment' in added:
                added['Environment'] = [
                    ecs.Environment(**m) for m in added['Environment']
                ]
            if 'ExtraHosts' in added:
                added['ExtraHosts'] = [
                    ecs.HostEntry(**m) for m in added['ExtraHosts']
                ]
            if 'LinuxParameters' in added:
                added['LinuxParameters'] = [
                    ecs.LinuxParameters(**m) for m in added['LinuxParameters']
                ]
            if 'MountPoints' in added:
                added['MountPoints'] = [
                    ecs.MountPoint(**m) for m in added['MountPoints']
                ]
            if 'Ulimit' in added:
                added['Ulimit'] = [ecs.Ulimit(**m) for m in added['Ulimit']]
            if 'VolumesFrom' in added:
                added['VolumesFrom'] = [
                    ecs.VolumesFrom(**m) for m in added['VolumesFrom']
                ]
            # munge memory
            if not 'Memory' in added and not 'MemoryReservation' in added:
                added['MemoryReservation'] = self.vars['Memory']

            attributes = added.copy()
        else:
            attributes = dict()

        # merge in required attributes.
        attributes.update(required)
        return attributes
))

TaskDefinition = t.add_resource(ecs.TaskDefinition(
    "TaskDefinition",
    DependsOn=TaskExecutionPolicy,
    RequiresCompatibilities=["FARGATE"],
    Cpu="512",
    Memory="1GB",
    NetworkMode="awsvpc",
    ExecutionRoleArn=GetAtt(TaskExecutionRole, "Arn"),
    ContainerDefinitions=[
        ecs.ContainerDefinition(
            Name="nginx-container",
            Image=Ref(NginxImage),
            Essential=True,
            PortMappings=[ecs.PortMapping(ContainerPort=80)],
            LogConfiguration=ecs.LogConfiguration(
                LogDriver="awslogs",
                Options={"awslogs-group": Ref(CWLogGroup),
                         "awslogs-region": Ref("AWS::Region"),
                         "awslogs-stream-prefix": "nginx-container"}
            )
        )
    ]
))

Service = t.add_resource(ecs.Service(
    "Service",
    DependsOn=ALBListener,
    Cluster=Ref(ECSCluster),
    DesiredCount=1,
t.add_resource(
    TaskDefinition(
        "task",
        ContainerDefinitions=[
            ContainerDefinition(
                Image=Join("", [
                    Ref("AWS::AccountId"), ".dkr.ecr.",
                    Ref("AWS::Region"), ".amazonaws.com", "/",
                    ImportValue("helloworld-repo"), ":",
                    Ref("Tag")
                ]),
                Memory=32,
                Cpu=256,
                Name="helloworld",
                PortMappings=[ecs.PortMapping(ContainerPort=3000)])
        ],
    ))

t.add_resource(
    Role(
        "ServiceRole",
        AssumeRolePolicyDocument=Policy(Statement=[
            Statement(Effect=Allow,
                      Action=[AssumeRole],
                      Principal=Principal("Service", ["ecs.amazonaws.com"]))
        ]),
        Path="/",
        ManagedPolicyArns=[
            'arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceRole'
        ]))
Ejemplo n.º 18
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        #SFFU## Save for future use
        #SFFU#environment = []
        #SFFU#for k, v in variables['ContainerEnvironmentVars'].iteritems():
        #SFFU#    environment.append(
        #SFFU#        ecs.Environment(
        #SFFU#            Name=k,
        #SFFU#            Value=v,
        #SFFU#        )
        #SFFU#    )

        #SFFU## Save for future use
        #SFFU#links = []
        #SFFU#for link in variables['ContainerLinks']:
        #SFFU#    links.append(link)

        portmappings = []
        #SFFU#for k, v in variables['ContainerEnvironmentVars'].iteritems():
        #SFFU#    environment.append(
        #SFFU#        ecs.Environment(
        #SFFU#            Name=k,
        #SFFU#            Value=v,
        #SFFU#        )
        #SFFU#    )
        for hp, cp in variables['ContainerPorts'].iteritems():
            portmappings.append(
                ecs.PortMapping(
                    HostPort=hp,
                    ContainerPort=cp,
                ))
        #old#for port in variables['ContainerPorts']:
        #old#    portmappings.append(
        #old#        ecs.PortMapping(
        #old#            ContainerPort=port,
        #old#            HostPort=port
        #old#        )
        #old#    )

        ecscontainerdef = ecs.ContainerDefinition(
            #SFFU## Save for future use
            #SFFU#Command=[
            #SFFU#    variables['ContainerCommand'].ref,
            #SFFU#],
            #SFFU#EntryPoint=[
            #SFFU#    variables['ContainerEntryPoint'].ref,
            #SFFU#],
            #SFFU#Environment=environment,
            #SFFU#Links=links,
            Image=Join(
                '',
                [
                    Ref('AWS::AccountId'),
                    '.dkr.ecr.',
                    Ref('AWS::Region'),
                    '.amazonaws.com/',
                    variables['App'].ref,
                    '-',
                    variables['ContainerName'].ref,
                    #SFOU#'-',
                    #SFOU#variables['EnvironmentName'].ref
                ]),
            LogConfiguration=ecs.LogConfiguration(
                LogDriver='awslogs',
                Options={
                    'awslogs-group': variables['CwLogGroupName'].ref,
                    'awslogs-region': Ref('AWS::Region'),
                    'awslogs-stream-prefix': 'ecs'
                }),
            Name=variables['ContainerName'].ref,
            #SFOU#PortMappings=[
            #SFOU#    ecs.PortMapping(
            #SFOU#        ContainerPort=variables['ContainerPort'].ref
            #SFOU#    )
            #SFOU#]
            PortMappings=portmappings,
        )

        ecstaskdefinition = template.add_resource(
            ecs.TaskDefinition(
                'EcsTaskDefinition',
                ContainerDefinitions=[ecscontainerdef],
                Cpu=variables['TaskCpu'].ref,
                Memory=variables['TaskMem'].ref,
                ExecutionRoleArn=variables['ExecutionRoleArn'].ref,
                TaskRoleArn=variables['TaskRoleArn'].ref,
                Family=Join('-', [
                    variables['ContainerName'].ref,
                    variables['EnvironmentName'].ref
                ]),
                NetworkMode=variables['NetworkMode'].ref,
                RequiresCompatibilities=[variables['LaunchType'].ref],
                # for future reference (need to add imports and variables)
                #Volumes=[
                #    Volume(
                #        Name=variables['VolumeName'].ref,
                #        Host=Host(SourcePath=variables['VolumeSourcePath'].ref
                #    )
                #],
            ))

        template.add_output(
            Output("{}Arn".format(ecstaskdefinition.title),
                   Description="ARN of the Task Definition",
                   Value=Ref(ecstaskdefinition),
                   Export=Export(
                       Sub('${AWS::StackName}-%sArn' %
                           ecstaskdefinition.title))))