コード例 #1
0
    def create_function(self):
        t = self.template
        variables = self.get_variables()

        self.function = t.add_resource(
            awslambda.Function(
                "Function",
                Code=self.code(),
                DeadLetterConfig=self.dead_letter_config(),
                Description=variables["Description"] or NoValue,
                Environment=self.environment(),
                Handler=variables["Handler"],
                KmsKeyArn=variables["KmsKeyArn"] or NoValue,
                MemorySize=variables["MemorySize"],
                Role=self.role_arn,
                Runtime=variables["Runtime"],
                Timeout=variables["Timeout"],
                VpcConfig=self.vpc_config(),
            )
        )

        t.add_output(
            Output("FunctionName", Value=self.function.Ref())
        )
        t.add_output(
            Output("FunctionArn", Value=self.function.GetAtt("Arn"))
        )

        self.function_version = t.add_resource(
            awslambda.Version(
                "LatestVersion",
                FunctionName=self.function.Ref()
            )
        )

        t.add_output(
            Output("LatestVersion",
                   Value=self.function_version.GetAtt("Version"))
        )
        t.add_output(
            Output("LatestVersionArn",
                   Value=self.function_version.Ref())
        )

        alias_name = variables["AliasName"]
        if alias_name:
            self.alias = t.add_resource(
                awslambda.Alias(
                    "Alias",
                    Name=alias_name,
                    FunctionName=self.function.Ref(),
                    FunctionVersion=variables["AliasVersion"] or "$LATEST",
                )
            )

            t.add_output(Output("AliasArn", Value=self.alias.Ref()))
コード例 #2
0
    def register_resources_template(self, template):
        """Register the lambda Function into the troposphere template. If
        this function requires a custom Role, register it too."""

        role = self.get_role()
        depends_on = []
        if isinstance(role, iam.Role):
            template.add_resource(role)
            depends_on.append(role.name)
            role = troposphere.GetAtt(role, 'Arn')

        template.add_parameter(
            troposphere.Parameter(
                utils.valid_cloudformation_name(self.name, "s3version"),
                Type="String",
            ))

        extra = {}
        if self.settings.get('vpc'):
            vpc = self.project.get_resource('vpc::{}'.format(
                self.settings.get('vpc')))

            if isinstance(vpc.settings['security-groups'], troposphere.Ref):
                vpc.settings[
                    'security-groups']._type = 'List<AWS::EC2::SecurityGroup::Id>'

            if isinstance(vpc.settings['subnet-ids'], troposphere.Ref):
                vpc.settings['subnet-ids']._type = 'List<AWS::EC2::Subnet::Id>'

            extra['VpcConfig'] = awslambda.VPCConfig(
                SecurityGroupIds=vpc.settings['security-groups'],
                SubnetIds=vpc.settings['subnet-ids'])

        function = template.add_resource(
            awslambda.Function(self.in_project_cf_name,
                               DependsOn=depends_on,
                               Code=awslambda.Code(
                                   S3Bucket=troposphere.Ref("CodeBucket"),
                                   S3Key=self.get_bucket_key(),
                                   S3ObjectVersion=troposphere.Ref(
                                       utils.valid_cloudformation_name(
                                           self.name, "s3version")),
                               ),
                               Description=self.settings.get(
                                   'description', ''),
                               Handler=self.get_handler(),
                               MemorySize=self.get_memory(),
                               Role=role,
                               Runtime=self.get_runtime(),
                               Timeout=self.get_timeout(),
                               **extra))

        lambda_version = 'lambda:contrib_lambdas:version'
        lambda_ref = troposphere.GetAtt(self.project.reference(lambda_version),
                                        'Arn')
        if not self.in_project_name.startswith('lambda:contrib_lambdas:'):
            lambda_version = '{}:current'.format(lambda_version)
            lambda_ref = troposphere.Ref(
                self.project.reference(lambda_version))

        version = template.add_resource(
            LambdaVersion.create_with(
                utils.valid_cloudformation_name(self.name, "Version"),
                DependsOn=[
                    self.project.reference(lambda_version), function.name
                ],
                lambda_arn=lambda_ref,
                FunctionName=troposphere.Ref(function),
                S3ObjectVersion=troposphere.Ref(
                    utils.valid_cloudformation_name(self.name, "s3version")),
            ))

        alias = template.add_resource(
            awslambda.Alias(
                self.current_alias_cf_name,
                DependsOn=[version.name],
                FunctionName=troposphere.Ref(function),
                FunctionVersion=troposphere.GetAtt(version, "Version"),
                Name="current",
            ))
        if self._get_true_false('cli-output', 't'):
            template.add_output([
                troposphere.Output(
                    utils.valid_cloudformation_name("Clioutput",
                                                    self.in_project_name),
                    Value=troposphere.Ref(alias),
                )
            ])
コード例 #3
0
    def build_template(self):

        deploy_alias = False

        t = self._init_template()

        self.jinja_env_vars()

        role_param = t.add_parameter(
            Parameter(self.role.output_role_arn(), Type='String'))
        bucket_ref = t.add_parameter(
            Parameter(self.s3_bucket.output_bucket_name(), Type='String'))

        if self._deploying:
            if not self.uploaded and self._bucket_name():
                deploy_alias = True
                self._determine_code_versions()
                logger.info("S3 Key: {}".format(self.zip_name))

        func = t.add_resource(
            awslambda.Function(
                '{}Function'.format(self.get_stack_name()),
                FunctionName=self.get_stack_name(),
                Handler=self.handler,
                MemorySize=self.memory,
                Timeout=self.timeout,
                Runtime=self.runtime,
                Role=Ref(role_param),
                Environment=awslambda.Environment(Variables=self.vars),
                Code=awslambda.Code(S3Bucket=Ref(bucket_ref),
                                    S3Key=self.zip_name)))

        if self.s3_version:
            func.Code.S3ObjectVersion = self.s3_version

        # vpc mode
        if self.vpc_stack is not None:

            if self.public_subnet:
                subnets = self.vpc_stack.output_public_subnets()
            else:
                subnets = self.vpc_stack.output_private_subnets()

            subnet_refs = [
                Ref(utils.ensure_param(t, val, 'String')) for val in subnets
            ]
            func.VpcConfig = awslambda.VPCConfig(SubnetIds=subnet_refs,
                                                 SecurityGroupIds=[])

            for sg in self.security_groups:
                sg_ref = Ref(
                    utils.ensure_param(t, sg.output_security_group(),
                                       'String'))
                func.VpcConfig.SecurityGroupIds.append(sg_ref)

        if deploy_alias is True:
            for v in self.aliases:
                t.add_resource(
                    awslambda.Alias('{}Alias'.format(v['name']),
                                    FunctionName=Ref(func),
                                    Name=v['name'],
                                    FunctionVersion=v['version']))

        if len(self.event_sources) > 0:
            for s in self.event_sources:
                src = s['src']
                args = s['args']
                if isinstance(src, dynamodb.DynamoTable):
                    p = t.add_parameter(
                        Parameter(src.output_stream(), Type='String'))
                    t.add_resource(
                        awslambda.EventSourceMapping(
                            'LambdaDynamo{}'.format(src.name),
                            FunctionName=Ref(func),
                            EventSourceArn=Ref(p),
                            StartingPosition='LATEST'))
                if isinstance(src, sqs.Queue):
                    p = t.add_parameter(
                        Parameter(src.output_queue_arn(), Type='String'))
                    t.add_resource(
                        awslambda.EventSourceMapping(
                            'LambdaSQS{}'.format(src.name),
                            FunctionName=Ref(func),
                            EventSourceArn=Ref(p),
                            BatchSize=args.get('BatchSize', 1)))

        for k, v in enumerate(self.perms):
            v.build(t, funv, k)

        t.add_output([
            Output('FunctionName', Value=Ref(func)),
            Output('FunctionArn', Value=GetAtt(func, "Arn"))
        ])

        return t