Ejemplo n.º 1
0
    def build(self, t):

        evt = t.add_resource(
            events.Rule('{}Event'.format(self.name), Targets=[]))
        if self.schedule is not None:
            evt.ScheduleExpression = self.schedule
        if self.enabled:
            evt.State = 'ENABLED'
        else:
            evt.State = 'DISABLED'

        for val in self.targets:
            tg = val[0]
            r = val[1]
            role_ref = ensure_param(t, r.output_role_arn())  # noqa

            target = events.Target()

            if isinstance(tg, (awslambda.LambdaStack)):
                func_name_ref = ensure_param(t, tg.output_func_name())
                func_arn_ref = ensure_param(t, tg.output_func_arn())
                target.Id = tg.get_stack_name()
                target.Arn = Ref(func_arn_ref)
                t.add_resource(
                    tlambda.Permission('{}EventPerm'.format(
                        tg.get_stack_name()),
                                       Action='lambda:invokeFunction',
                                       Principal='events.amazonaws.com',
                                       FunctionName=Ref(func_name_ref),
                                       SourceArn=GetAtt(evt, 'Arn')))
            evt.Targets.append(target)
Ejemplo n.º 2
0
    def invoke_permission(
        self,
        name_suffix: str,
        service: str,
        source_arn: str,
        source_account: Optional[str] = None,
    ) -> awslambda.Permission:
        """Create a Lambda Permission object for a given service.

        :param name_suffix: a suffix used in the object name
        :param service: service name (without amazonaws.com domain name)
        :param source_arn: arn of the resource that can access the lambda
        :param source_account: account that holds the resource. This is
            mandatory only when using S3 as a service as a bucket arn is
            not linked to an account.
        :return: an AWSObject
        """
        params = {
            "Action": "lambda:InvokeFunction",
            "FunctionName": self.ref,
            "Principal": f"{service}.amazonaws.com",
            "SourceArn": source_arn,
        }
        if service == "s3":
            assert source_account is not None
        if source_account is not None:
            params["SourceAccount"] = source_account

        return awslambda.Permission(name_to_id(self.name + name_suffix), **params)
Ejemplo n.º 3
0
 def lambda_policy_adder(self, name, principal):
     self.template.add_resource(
         awslambda.Permission("LambdaPermissionPolicy",
                              DependsOn=name,
                              Action="lambda:InvokeFunction",
                              FunctionName=name,
                              Principal=principal))
Ejemplo n.º 4
0
    def create_scheduler(self):
        variables = self.get_variables()
        troposphere_events_rule = variables["CloudwatchEventsRule"]
        aws_lambda_arns = {}

        # iterate over targets in the event Rule & gather aws_lambda_arns.
        for target in getattr(troposphere_events_rule, "Targets", []):
            if target.Arn.startswith("arn:aws:lambda:"):
                safe_id = cf_safe_name(target.Id)
                aws_lambda_arns[safe_id] = target.Arn

        # schedule a Cloudwatch event rule to invoke the Targets.
        rule = self.template.add_resource(troposphere_events_rule)

        # allow cloudwatch to invoke on any of the given lambda targets.
        for event_rule_target_id, aws_lambda_arn in aws_lambda_arns.items():
            self.template.add_resource(
                awslambda.Permission(
                    "PermToInvokeFunctionFor{}".format(event_rule_target_id),
                    Principal="events.amazonaws.com",
                    Action="lambda:InvokeFunction",
                    FunctionName=aws_lambda_arn,
                    SourceArn=rule.GetAtt("Arn")
                )
            )
Ejemplo n.º 5
0
    def build(self, t, func, key):

        perm = t.add_resource(
            awslambda.Permission('{}Perm'.format(key),
                                 Action=self.action,
                                 Principal=self.principal,
                                 FunctionName=Ref(func)))
Ejemplo n.º 6
0
def build_lambda_permission(name: str) -> awslambda.Permission:
    permission = awslambda.Permission(lambda_permission_name(name))

    permission.Action = "lambda:InvokeFunction"
    permission.FunctionName = GetAtt(lambda_function_name(name), "Arn")
    permission.Principal = "events.amazonaws.com"
    permission.SourceArn = GetAtt(rule_name(name), "Arn")

    return permission
Ejemplo n.º 7
0
 def register_destination_publish_permission(self, template):
     template.add_resource(
         awslambda.Permission(
             utils.valid_cloudformation_name(
                 self.bucket_notification_configuration.name, self.id,
                 'permission'),
             Action="lambda:InvokeFunction",
             FunctionName=self.get_destination_arn(),
             Principal="s3.amazonaws.com",
             SourceAccount=troposphere.Ref(troposphere.AWS_ACCOUNT_ID),
         ))
Ejemplo n.º 8
0
    def add_api(self):
        api = self.add_resource(
            apigatewayv2.Api(
                'HttpApi',
                Name=StackName,
                Description=Join(' ',
                                 [Ref(self.domain), 'Terraform Registry']),
                ProtocolType='HTTP',
                Target=Ref(self._lambda_function),
            ))

        self.add_resource(
            awslambda.Permission(
                f'ApigatewayPermission',
                Principal='apigateway.amazonaws.com',
                Action='lambda:InvokeFunction',
                FunctionName=Ref(self._lambda_function),
                SourceArn=Join('', [
                    'arn:aws:execute-api:', Region, ':', AccountId, ':',
                    Ref(api), '/*'
                ])))

        domain = self.add_resource(
            apigatewayv2.DomainName('HttpApiDomain',
                                    DomainName=Ref(self.domain),
                                    DomainNameConfigurations=[
                                        apigatewayv2.DomainNameConfiguration(
                                            CertificateArn=Ref(
                                                self.certificate), )
                                    ]))

        mapping = self.add_resource(
            apigatewayv2.ApiMapping('Mapping',
                                    DomainName=Ref(domain),
                                    ApiId=Ref(api),
                                    Stage='$default'))

        dns_record = self.add_resource(
            route53.RecordSetGroup(
                'ApiDnsRecord',
                HostedZoneId=Ref(self.hosted_zone),
                RecordSets=[
                    route53.RecordSet(
                        Name=Ref(self.domain),
                        AliasTarget=route53.AliasTarget(
                            DNSName=GetAtt(domain, 'RegionalDomainName'),
                            HostedZoneId=GetAtt(domain,
                                                'RegionalHostedZoneId')),
                        Type='A')
                ]))
Ejemplo n.º 9
0
    def add_lambda_sns_topic_subscription(self, title, topic,
                                          aws_lambda_function):
        self.template.add_resource(
            sns.SubscriptionResource(title + 'LambdaSubscriptionToTopic',
                                     Protocol='lambda',
                                     TopicArn=topic,
                                     Endpoint=GetAtt(aws_lambda_function,
                                                     'Arn')))

        self.template.add_resource(
            awslambda.Permission(title + 'LambdaSubscriptionToTopicPermission',
                                 FunctionName=Ref(aws_lambda_function),
                                 Action='lambda:InvokeFunction',
                                 Principal='sns.amazonaws.com',
                                 SourceArn=topic))
Ejemplo n.º 10
0
    def build_subscription(self, t, topic):

        policy = t.add_resource(
            iam.Role(
                "{}SlackSNSRole".format(self.name),
                AssumeRolePolicyDocument=aws.Policy(Statement=[
                    aws.Statement(Action=[awacs.sts.AssumeRole],
                                  Effect=aws.Allow,
                                  Principal=aws.Principal(
                                      "Service", ["lambda.amazonaws.com"]))
                ]),
                Path="/",
                Policies=[
                    iam.Policy(
                        PolicyName='snspublic',
                        PolicyDocument=aws.PolicyDocument(Statement=[
                            aws.Statement(Effect=aws.Allow,
                                          Action=[
                                              awacs.sns.Publish,
                                              awacs.logs.PutLogEvents,
                                              awacs.logs.CreateLogGroup,
                                              awacs.logs.CreateLogStream,
                                          ],
                                          Resource=["*"])
                        ]))
                ],
                ManagedPolicyArns=[
                    # "arn:aws:iam::aws:policy/AdministratorAccess"
                ]))

        code = ["import sys"]
        # make lambda function
        fn = t.add_resource(
            awslambda.Function('{}SlackTopicFN'.format(self.name),
                               Handler='index.handle',
                               Runtime='python3.6',
                               Role=GetAtt(policy, "Arn"),
                               Code=awslambda.Code(ZipFile=Join("", code))))

        t.add_resource(
            awslambda.Permission('{}LambdaPerm'.format(self.name),
                                 Action='lambda:InvokeFunction',
                                 FunctionName=GetAtt(fn, "Arn"),
                                 SourceArn=Ref(topic),
                                 Principal="sns.amazonaws.com"))

        return ("lambda", GetAtt(fn, "Arn"))
Ejemplo n.º 11
0
    def declare_route(self, route: Route,
                      integration: Ref | str) -> list[AWSObject]:
        """Declare a route.

        :param route: the route definition
        :param integration: arn of the integration to use for this route
        :return: a list of AWSObjects to be added to the stack
        """
        result = []
        id_prefix = name_to_id(self.name + route.method + route.route)

        route_params = {
            "ApiId":
            self.ref,
            "AuthorizationType":
            route.auth.value,
            "RouteKey":
            f"{route.method} {route.route}",
            "Target":
            Sub("integrations/${integration}",
                dict_values={"integration": integration}),
        }
        if route.authorizer_name:
            route_params["AuthorizerId"] = Ref(
                name_to_id(route.authorizer_name))

        result.append(apigatewayv2.Route(id_prefix + "Route", **route_params))

        result.append(
            awslambda.Permission(
                id_prefix + "LambdaPermission",
                Action="lambda:InvokeFunction",
                FunctionName=self.lambda_arn,
                Principal="apigateway.amazonaws.com",
                SourceArn=Sub(
                    "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:"
                    "${api}/$default/${route_arn}",
                    dict_values={
                        "api": self.ref,
                        "route_arn": f"{route.method}{route.route}",
                    },
                ),
            ))
        return result
Ejemplo n.º 12
0
    def add_lambda_events_rule(self, title, function, **kwargs):
        t = self.template

        schedule_rule = t.add_resource(
            events.Rule(title + 'ScheduleRule',
                        Targets=[
                            events.Target(Arn=GetAtt(function, 'Arn'),
                                          Id=title + 'LambdaFunction')
                        ],
                        **kwargs))

        perm = t.add_resource(
            awslambda.Permission(title + 'LambdaInvokePermission',
                                 FunctionName=Ref(function),
                                 Action='lambda:InvokeFunction',
                                 Principal='events.amazonaws.com',
                                 SourceArn=GetAtt(schedule_rule, 'Arn')))

        return schedule_rule, perm
Ejemplo n.º 13
0
def add_lambda_scheduler(*, template_res, cron, lambda_function_name,
                         lambda_function_arn):
    lambda_function = ''.join(
        [a.title() for a in lambda_function_name.split('_')])
    event_target = Target(f'{lambda_function}EventTarget',
                          Arn=lambda_function_arn,
                          Id=f'{lambda_function}FunctionEventTarget')
    scheduler = template_res.add_resource(
        Rule(
            f'ScheduledRule{lambda_function}',
            ScheduleExpression=cron,
            # http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
            Description=f'Scheduled Event for Lambda {lambda_function_name}',
            State="ENABLED",
            Targets=[event_target]))
    add_permission = template_res.add_resource(
        awslambda.Permission(f'AccessLambda{lambda_function}',
                             Action='lambda:InvokeFunction',
                             FunctionName=f'{lambda_function_name}',
                             Principal='events.amazonaws.com',
                             SourceArn=GetAtt(scheduler, 'Arn')))
Ejemplo n.º 14
0
    Runtime="python3.7",
    MemorySize=128,
    Role=GetAtt(role, "Arn"))

### API Gateway
api = apigatewayv2.Api("HttpApi",
                       Name=f"api-contact-form-{cdomain}",
                       Description=f"API Gateway for contact form on {domain}",
                       ProtocolType="HTTP",
                       Target=GetAtt(lambda_function, "Arn"))

api_gateway_lambda_permission = awslambda.Permission(
    "ApiGatewayLambdaPermission",
    Action="lambda:InvokeFunction",
    FunctionName=GetAtt(lambda_function, "Arn"),
    Principal="apigateway.amazonaws.com",
    SourceArn=Join(values=[
        "arn", "aws", "execute-api",
        Ref("AWS::Region"),
        Ref("AWS::AccountId"),
        Join(values=[Ref(api), "*"], delimiter="/")
    ],
                   delimiter=":"))

t = Template()
t.add_resource(topic)
t.add_resource(role)
t.add_resource(lambda_function)
t.add_resource(api)
t.add_resource(api_gateway_lambda_permission)
print(t.to_yaml())
            'lambdas/update_security_groups.py')),
        Environment=awslambda.Environment(
            Variables={'REGIONS': Ref(param_regions)}),
        Handler='index.lambda_handler',
        Role=GetAtt(update_function_execution_role, 'Arn'),
        Runtime='python2.7',
        MemorySize='128',
        Timeout='300',
    ))

ip_space_changed_topic = 'arn:aws:sns:us-east-1:806199016981:AmazonIpSpaceChanged'

update_function_lambda_permission = t.add_resource(
    awslambda.Permission('LambdaPermission',
                         FunctionName=Ref(update_security_groups_function),
                         Action='lambda:InvokeFunction',
                         Principal='sns.amazonaws.com',
                         SourceArn=ip_space_changed_topic))

custom_resource_execution_role = t.add_resource(
    iam.Role(
        'CustomResourceExecutionRole',
        AssumeRolePolicyDocument=Policy(Statement=[
            Statement(Effect=Allow,
                      Action=[awacs.sts.AssumeRole],
                      Principal=Principal('Service', ['lambda.amazonaws.com']))
        ]),
        ManagedPolicyArns=[
            'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
        ],
        Policies=[
                ]))
        ]))

# Create the Event Target
GuardDutyEventTarget = Target("GuardDutyEventTarget",
                              Arn=GetAtt('GuardDutyToSlackFunction', 'Arn'),
                              Id="GuardDutyToSlackFunction")

# Create the Event Rule
GuardDutyEventRule = t.add_resource(
    Rule("GuardDutyEventRule",
         EventPattern={
             "source": ["aws.guardduty"],
             "detail-type": ["GuardDuty Finding"]
         },
         Description="GuardDuty CloudWatch Event Rule",
         State="ENABLED",
         Targets=[GuardDutyEventTarget]))

# Create invoke Permission
APILambdaPermission = t.add_resource(
    awslambda.Permission("APILambdaPermission",
                         DependsOn="GuardDutyToSlackFunction",
                         Action="lambda:InvokeFunction",
                         FunctionName=GetAtt('GuardDutyToSlackFunction',
                                             'Arn'),
                         Principal="events.amazonaws.com",
                         SourceArn=GetAtt('GuardDutyEventRule', 'Arn')))

print t.to_json()
# Event subscription - RDS will notify SNS when backup is started and finished
template.add_resource(
    rds.EventSubscription("RDSBackupEvent",
                          Enabled=True,
                          EventCategories=["backup"],
                          SourceType="db-instance",
                          SnsTopicArn=Ref(rds_topic),
                          SourceIds=If("UseAllDatabases", Ref(AWS_NO_VALUE),
                                       Ref(databases_to_use_parameter))))

# Permission for SNS to trigger the Lambda
template.add_resource(
    awslambda.Permission("SNSPermissionForLambda",
                         Action="lambda:invokeFunction",
                         FunctionName=Ref(backup_rds_function),
                         Principal="sns.amazonaws.com",
                         SourceArn=Ref(rds_topic)))

schedule_event = template.add_resource(
    events.Rule("AuroraBackupEvent",
                Condition="IncludeAurora",
                Description="Copy Aurora clusters to another region",
                ScheduleExpression="rate(1 day)",
                State="ENABLED",
                Targets=[
                    events.Target(Arn=GetAtt(backup_rds_function, "Arn"),
                                  Id="backup_rds_function")
                ]))

# Permission for CloudWatch Events to trigger the Lambda
Ejemplo n.º 18
0
        Handler='index.lambda_handler',
        Role=GetAtt(lambda_execution_role, 'Arn'),
        Runtime='python2.7',
        MemorySize='512',
        Timeout='120',
        Environment=awslambda.Environment(Variables={
            'DST_BUCKET': Ref(dst_bucket),
            # 'DST_PREFIX': Ref(param_dst_prefix)
        }),
    ))

updater_lambda_permission = t.add_resource(
    awslambda.Permission(
        'LambdaPermission',
        FunctionName=Ref(lambda_function),
        Action='lambda:InvokeFunction',
        Principal='s3.amazonaws.com',
        SourceAccount=Sub('${AWS::AccountId}'),
        SourceArn=Join('', ['arn:aws:s3:::', Ref(src_bucket)]),
    ))

#
# Output
#
t.add_output([
    Output('SourceBucketName',
           Description='S3 bucket',
           Value=Ref(src_bucket),
           Export=Export(Sub('${AWS::StackName}-SourceBucketName'))),
    Output('DestinationBucketName',
           Description='S3 bucket',
           Value=Ref(dst_bucket),
Ejemplo n.º 19
0
def archive_invocation_permission(archive_function, archive_event_rule):
    return awslambda.Permission('ArchiveInvocationPermission',
                                Action='lambda:InvokeFunction',
                                FunctionName=Ref(archive_function),
                                Principal='events.amazonaws.com',
                                SourceArn=GetAtt(archive_event_rule, 'Arn'))
Ejemplo n.º 20
0
    def add_api(self):
        rest_api = self.add_resource(
            apigateway.RestApi(
                'Api',
                Description=Join(' ',
                                 [Ref(self.domain), 'Terraform Registry']),
                Name=StackName))

        methods = self.add_registry_api(rest_api)
        methods += [self.add_service_discovery_api(rest_api)]

        self.add_resource(
            awslambda.Permission(
                f'ApigatewayPermission',
                Principal='apigateway.amazonaws.com',
                Action='lambda:InvokeFunction',
                FunctionName=Ref(self._lambda_function),
                SourceArn=Join('', [
                    'arn:aws:execute-api:', Region, ':', AccountId, ':',
                    Ref(rest_api), '/*'
                ])))

        deployment_id = 'ApiDeployment' + ''.join(
            random.choice(string.ascii_letters) for _ in range(5))

        deployment = self.add_resource(
            apigateway.Deployment(deployment_id,
                                  Description=self._build_version,
                                  RestApiId=Ref(rest_api),
                                  DependsOn=methods,
                                  DeletionPolicy=Retain))

        stage = self.add_resource(
            apigateway.Stage('ApiStage',
                             MethodSettings=[
                                 apigateway.MethodSetting(
                                     HttpMethod='*',
                                     LoggingLevel='INFO',
                                     MetricsEnabled=True,
                                     ResourcePath='/*',
                                     DataTraceEnabled=True,
                                 )
                             ],
                             TracingEnabled=True,
                             StageName='prd',
                             RestApiId=Ref(rest_api),
                             DeploymentId=Ref(deployment),
                             DependsOn=[deployment]))

        domain = self.add_resource(
            apigateway.DomainName(
                'ApiDomain',
                DomainName=Ref(self.domain),
                CertificateArn=Ref(self.certificate),
                EndpointConfiguration=apigateway.EndpointConfiguration(
                    Types=['EDGE'])))

        mapping = self.add_resource(
            apigateway.BasePathMapping('Mapping',
                                       DomainName=Ref(domain),
                                       RestApiId=Ref(rest_api),
                                       Stage='prd',
                                       DependsOn=['ApiStage']))

        dns_record = self.add_resource(
            route53.RecordSetGroup('ApiDnsRecord',
                                   HostedZoneId=Ref(self.hosted_zone),
                                   RecordSets=[
                                       route53.RecordSet(
                                           Name=Ref(self.domain),
                                           AliasTarget=route53.AliasTarget(
                                               DNSName=GetAtt(
                                                   domain,
                                                   'DistributionDomainName'),
                                               HostedZoneId='Z2FDTNDATAQYW2'),
                                           Type='A')
                                   ]))
Ejemplo n.º 21
0
account = t.add_resource(apigateway.Account(
    "Account",
    DependsOn=api.title,
    CloudWatchRoleArn=ImportValue(
        Sub("${AccessStack}-SshCaApiRole")
    )
))

invoke_perm_get = t.add_resource(awslambda.Permission(
    "InvokePermGet",
    Action="lambda:InvokeFunction",
    FunctionName=LAMBDA_ARN,
    Principal="apigateway.amazonaws.com",
    SourceArn=Join(":", [
        "arn:aws:execute-api",
        Ref("AWS::Region"),
        Ref("AWS::AccountId"),
        Join("", [
            Ref(api),
            "/*/GET/*"
        ])])
))
invoke_perm_post = t.add_resource(awslambda.Permission(
    "InvokePermPost",
    Action="lambda:InvokeFunction",
    FunctionName=LAMBDA_ARN,
    Principal="apigateway.amazonaws.com",
    SourceArn=Join(":", [
        "arn:aws:execute-api",
        Ref("AWS::Region"),
        Ref("AWS::AccountId"),
Ejemplo n.º 22
0
def invocation_permission(name, function, event_rule):
    return awslambda.Permission(name,
                                Action='lambda:InvokeFunction',
                                FunctionName=Ref(function),
                                Principal='events.amazonaws.com',
                                SourceArn=GetAtt(event_rule, 'Arn'))
Ejemplo n.º 23
0
    def build_template(self):

        t = self._init_template()

        swag_data = []
        for i in range(0, 4):
            swag_data.append(
                Ref(
                    t.add_parameter(
                        Parameter('{}Swagger{}'.format(self.stack_name, i),
                                  Type='String',
                                  Default=' ',
                                  Description='Swagger Data #{}'.format(i)))))

        api = t.add_resource(
            apigateway.RestApi(
                '{}RestApi'.format(self.stack_name),
                Body=Join('', swag_data),
                EndpointConfiguration=apigateway.EndpointConfiguration(
                    Types=[self.ep_type])))

        if len(self.stages) <= 0:
            self.add_stage('prod')

        for stage in self.stages:
            deployment = t.add_resource(
                apigateway.Deployment(
                    '{}{}{}Deployment'.format(self.stack_name,
                                              md5str(self.template_str),
                                              stage),
                    RestApiId=Ref(api),
                    StageName=md5str(self.template_str + stage),
                ))
            stage_res = t.add_resource(
                apigateway.Stage(
                    '{}{}Stage'.format(self.stack_name, stage),
                    StageName=stage,
                    Description='{}{}'.format(self.stack_name, stage),
                    RestApiId=Ref(api),
                    DeploymentId=Ref(deployment),
                ))

        for func in self.lambda_funcs:
            func_param = t.add_parameter(
                Parameter(func.output_func_arn(),
                          Type='String',
                          Description='Function to grant invoke access to'))

            t.add_resource(
                awslambda.Permission(
                    'SwagFuncPerm{}'.format(func.output_func_name()),
                    SourceArn=Join("", [
                        'arn:aws:execute-api:',
                        Ref('AWS::Region'), ':',
                        Ref('AWS::AccountId'), ':',
                        Ref(api), "/*/*/*"
                    ]),
                    FunctionName=Ref(func_param),
                    Action='lambda:invokeFunction',
                    Principal='apigateway.amazonaws.com',
                    DependsOn="{}RestApi".format(self.stack_name)))

        t.add_output([
            Output('ApiId'.format(self.stack_name),
                   Description='Root id for API',
                   Value=Ref(api)),
            Output('ApiUrl'.format(self.stack_name),
                   Value=Join('', [
                       Ref(api), '.execute-api.',
                       Ref('AWS::Region'), '.amazonaws.com'
                   ]))
        ])

        return t
Ejemplo n.º 24
0
def archiveeach_invocation_permission(archiveeach_function, archiveeach_topic):
    return awslambda.Permission('ArchiveeachInvocationPermission',
                                Action='lambda:InvokeFunction',
                                FunctionName=Ref(archiveeach_function),
                                Principal='sns.amazonaws.com',
                                SourceArn=Ref(archiveeach_topic))
                           S3Key=Ref(param_lambda_file_name)),
                       Handler="lambda.lambda_handler",
                       MemorySize=128,
                       Role=GetAtt(lambda_role, "Arn"),
                       Runtime="python2.7",
                       Timeout=30))

api = template.add_resource(
    apigateway.RestApi("API", Description="My API", Name="MyAPI"))

api_lambda_permission = template.add_resource(
    awslambda.Permission("APILambdaPermission",
                         Action="lambda:InvokeFunction",
                         FunctionName=Ref(lambda_function),
                         Principal="apigateway.amazonaws.com",
                         SourceArn=Join("", [
                             "arn:aws:execute-api:",
                             Ref("AWS::Region"), ":",
                             Ref("AWS::AccountId"), ":",
                             Ref(api), "/*/GET/*"
                         ])))

api_first_resource = template.add_resource(
    apigateway.Resource("APIFirstResource",
                        ParentId=GetAtt(api, "RootResourceId"),
                        PathPart="{param1}",
                        RestApiId=Ref(api)))

api_first_method = template.add_resource(
    apigateway.Method(
        "APIFirstResourceMethodGET",
        ApiKeyRequired=False,
                "format": frmt
            })))

# create an EventBridge rule to kick off the lambda
arcgis_rule = template.add_resource(
    events.Rule(rule_name,
                ScheduleExpression=cron,
                Description="My Lambda CloudWatch Event",
                State="ENABLED",
                Targets=[
                    events.Target("MyLambdaTarget",
                                  Arn=GetAtt(arcgis_lambda.title, "Arn"),
                                  Id="MyLambdaId")
                ]))

# add permissions to the lambda to allow EventBridge to kick it off
arcgis_permission = template.add_resource(
    awslambda.Permission(
        perm_name,
        FunctionName=GetAtt(arcgis_lambda.title, 'Arn'),
        Action='lambda:InvokeFunction',
        Principal='events.amazonaws.com',
        SourceArn=GetAtt(arcgis_rule.title, 'Arn'),
    ))

# write the json template to a yaml file
template.to_yaml()
fh = open("template.yaml", "w")
fh.writelines(template.to_yaml())
fh.close()
    def generate_template(self, template):

        alias = Parameter("LambdaEnvAlias",
                          Default="int",
                          Description="Alias used to reference the lambda",
                          Type="String")
        template.add_parameter(aliasP)

        lambda_bucket = template.add_parameter(
            Parameter("LambdaBucket",
                      Type="String",
                      Default="go-lambda-hello-world",
                      Description=
                      "The S3 Bucket that contains the zip to bootstrap your "
                      "lambda function"))

        s3_key = template.add_parameter(
            Parameter("S3Key",
                      Type="String",
                      Default="main.zip",
                      Description=
                      "The S3 key that references the zip to bootstrap your "
                      "lambda function"))

        handler = template.add_parameter(
            Parameter(
                "LambdaHandler",
                Type="String",
                Default="event_handler.handler",
                Description="The name of the function (within your source code) "
                "that Lambda calls to start running your code."))

        memory_size = template.add_parameter(
            Parameter(
                "LambdaMemorySize",
                Type="Number",
                Default="128",
                Description="The amount of memory, in MB, that is allocated to "
                "your Lambda function.",
                MinValue="128"))

        timeout = template.add_parameter(
            Parameter("LambdaTimeout",
                      Type="Number",
                      Default="300",
                      Description=
                      "The function execution time (in seconds) after which "
                      "Lambda terminates the function. "))

        lambda_function = template.add_resource(
            Function(
                "LambdaGoHelloWorld",
                Code=Code(S3Bucket="go-lambda-hello-world", S3Key=Ref(s3_key)),
                Description="Go function used to demonstate sqs integration",
                Handler=Ref(handler),
                Role=GetAtt("LambdaExecutionRole", "Arn"),
                Runtime="go1.x",
                MemorySize=Ref(memory_size),
                FunctionName="go-lambda-hello-world",
                Timeout=Ref(timeout)))

        alias = template.add_resource(
            Alias("GolLambdaAlias",
                  Description="Alias for the go lambda",
                  FunctionName=Ref(lambda_function),
                  FunctionVersion="$LATEST",
                  Name=Ref(alias)))

        dead_letter_queue = template.add_resource(
            Queue("GoLambdaDeadLetterQueue",
                  QueueName=("golambdaqueue-dlq"),
                  VisibilityTimeout=30,
                  MessageRetentionPeriod=1209600,
                  MaximumMessageSize=262144,
                  DelaySeconds=0,
                  ReceiveMessageWaitTimeSeconds=0))

        go_helloworld_queue = template.add_resource(
            Queue("GoLambdaQueue",
                  QueueName=("golambdaqueue"),
                  VisibilityTimeout=1800,
                  RedrivePolicy=RedrivePolicy(deadLetterTargetArn=GetAtt(
                      dead_letter_queue, "Arn"),
                                              maxReceiveCount=3)))

        lambda_execution_role = template.add_resource(
            Role("LambdaExecutionRole",
                 Policies=[
                     iam.Policy(
                         PolicyName="GoFunctionRolePolicy",
                         PolicyDocument=Policy(Statement=[
                             Statement(Effect=Allow,
                                       Action=[
                                           Action("logs", "CreateLogGroup"),
                                           Action("logs", "CreateLogStream"),
                                           Action("logs", "PutLogEvents")
                                       ],
                                       Resource=["arn:aws:logs:*:*:*"]),
                             Statement(
                                 Effect=Allow,
                                 Action=[
                                     Action("sqs", "ChangeMessageVisibility"),
                                     Action("sqs", "DeleteMessage"),
                                     Action("sqs", "GetQueueAttributes"),
                                     Action("sqs", "ReceiveMessage")
                                 ],
                                 Resource=[GetAtt(go_helloworld_queue, "Arn")])
                         ]))
                 ],
                 AssumeRolePolicyDocument=Policy(Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   ["lambda.amazonaws.com"]))
                 ])))

        template.add_resource(
            awslambda.Permission(
                'QueueInvokePermission',
                FunctionName=GetAtt(lambda_function, 'Arn'),
                Action="lambda:InvokeFunction",
                Principal="sqs.amazonaws.com",
                SourceArn=GetAtt(go_helloworld_queue, 'Arn'),
            ))

        template.add_output(
            Output("LambdaHelloWorldQueue",
                   Value=GetAtt(go_helloworld_queue, "Arn"),
                   Export=Export("lambda-go-hello-world-queue"),
                   Description="Arn of the queue"))

        template.add_output(
            Output("LambdaHelloWorlFunction",
                   Value=Ref(alias),
                   Export=Export("lambda-go-hello-world-function"),
                   Description="Arn of the function"))
Ejemplo n.º 28
0
        role=lambda_exe_role,
        lambda_params={
            "Environment":
            awslambda.Environment(
                Variables={
                    'PREVIOUS_TIME_SSM_PARAM_NAME': Ref(ssm_previous_time),
                    'SCHEDULER_LAMBDA_NAME': Ref(hyp3_scheduler.scheduler)
                }),
            "MemorySize":
            128,
            "Timeout":
            300
        }))

find_new_target = events.Target("FindNewTarget",
                                Arn=GetAtt(find_new_granules, 'Arn'),
                                Id="FindNewFunction1")

find_new_event_rule = t.add_resource(
    events.Rule("FindNewGranulesSchedule",
                ScheduleExpression="rate(1 minute)",
                State="ENABLED",
                Targets=[find_new_target]))

PermissionForEventsToInvokeLambda = t.add_resource(
    awslambda.Permission("EventSchedulePermissions",
                         FunctionName=Ref(find_new_granules),
                         Action="lambda:InvokeFunction",
                         Principal="events.amazonaws.com",
                         SourceArn=GetAtt("FindNewGranulesSchedule", "Arn")))
Ejemplo n.º 29
0
        Description="Maintains EBS snapshots of tagged instances",
        Code=awslambda.Code(
            S3Bucket=Ref(s3_bucket_parameter),
            S3Key=Ref(source_zip_parameter),
        ),
        Handler="ebs-snapshots.lambda_handler",
        MemorySize=128,
        Role=GetAtt(lambda_role, "Arn"),
        Runtime="python3.6",
        Timeout=30))

schedule_event = template.add_resource(
    events.Rule("LambdaTriggerRule",
                Description="Trigger EBS snapshot Lambda",
                ScheduleExpression="rate(1 day)",
                State="ENABLED",
                Targets=[
                    events.Target(Arn=GetAtt(lambda_function, "Arn"),
                                  Id="ebs-snapshot-lambda")
                ]))

# Permission for CloudWatch Events to trigger the Lambda
template.add_resource(
    awslambda.Permission("EventsPermissionForLambda",
                         Action="lambda:invokeFunction",
                         FunctionName=Ref(lambda_function),
                         Principal="events.amazonaws.com",
                         SourceArn=GetAtt(schedule_event, "Arn")))

print(template.to_json())
Ejemplo n.º 30
0
def show_invocation_permission(show_function, show_event_rule):
    return awslambda.Permission('ShowInvocationPermission',
                                Action='lambda:InvokeFunction',
                                FunctionName=Ref(show_function),
                                Principal='events.amazonaws.com',
                                SourceArn=GetAtt(show_event_rule, 'Arn'))