Mazzy
Mazzy

Reputation: 14229

Create Lambda permission in serverless

I'm running into an issue with Serverless v1.5 (latest version currently available at the time of writing)

I've to add permission to the lambda function and I'm trying to achieve this by creating a CF template and running along with the deploy of the function:

resources:
  Resources:
    logsGroup:
      Type: "AWS::Lambda::Permission"
      Properties: 
        Action: lambda:InvokeFunction
        FunctionName: 
          Fn::GetAtt:
            - "${self:custom.${opt:stage}.name}"
            - "Arn"
        Principal: "logs.amazonaws.com"
        SourceAccount:
          Ref: "AWS::AccountId"
        SourceArn: "arn:aws:logs:${self:provider.region}:*:log-group:*:*"

This is how it should look like. My problem is that when I try to deploy it I get an error which says that the function is not created yet which is understandable. How can I overcome to this issue? Any ideas?

Upvotes: 8

Views: 4711

Answers (2)

Ulli
Ulli

Reputation: 2210

By default, Serverless creates your custom resources first, which makes sense as you usually put S3 buckets etc. there that your functions rely on.

In the end though, Serverless translates everything to a Cloudformation template, which you can see in the .serverless directory. What you will notice there is that your function names are suffixed with "LambdaFunction". So if you named your function "Foo", this is translated to "FooLambdaFunction". By that name, you can reference the function in a custom resource, which makes Cloudformation wait for the function before it creates the resource.

E.g.

functions:
  Foo:
    handler: functions/foo.handler
    name: foo-lambda
    description: Sample function
resources:
  Resources:
    PermissionToCallFoo:
      Type: "AWS::Lambda::Permission"
      Properties: 
        Action: lambda:InvokeFunction
        FunctionName: 
          Ref: FooLambdaFunction
        Principal: "logs.amazonaws.com"
  Outputs:
    FooArn:
      Value:
        Fn::GetAtt: 
          - FooLambdaFunction
          - Arn
      Export:
        Name: "FooArn"

Upvotes: 3

ironmanwaring
ironmanwaring

Reputation: 91

Not enough rep to add a comment - have you tried adding a DependsOn attribute to the Lambda Permission resource? Explicitly setting that property will result in CloudFormation waiting until the Lambda Function resource is created before creating this permission.

Also if you weren't already aware the .serverless folder that gets created in the root of your project contains the CloudFormation templates used by serverless, which can be helpful when troubleshooting unexpected CloudFormation behavior.

Upvotes: 4

Related Questions