Search code examples
amazon-web-servicesaws-lambdaaws-cloudformationaws-sam-cliaws-sam

Multiple Lambda functions from the sam.yml file


Still waiting for actual AWS support for this: https://github.com/aws-samples/aws-serverless-samfarm/issues/5

How is this supposed to work?

My use case is I have an API Gateway fronted lambda that writes events to an SNS topic. I have another lambda that is subscribed to that topic.

Could these lambdas be in separate repos? Yes. Is part of the purpose of using a pub/sub pattern to separate these two applications in the first place? Yes.

But this is a simple app. The topic won't be shared with other functions and the whole thing is self contained. It should all be deployed together ideally all in the same template.

I can easily add all the functions I want to my SAM template but how do I deploy them? Should they each have a different CodeURI? That mean I need to script copying and install each lambdas dependencies into a different folder then point the CodeURIs for each lambda in the template to the different folder.

Is there any better support for this?


Solution

  • You can have as many AWS::Serverless::Function resources in a single template as you want as long as they have a unique logical id.

    If you prefer to keep several lambda functions in a single repository you will have to provide different CodeUri for each lambda. For instance CodeUri: ./handler-my-lambda-one.zip and CodeUri: ./handler-my-lambda-two.zip.

    Usually, it's a good practice to have a Makefile in your repository that would have a build target responsible for preparing handler-my-lambda-*.zip something like:

    build: 
        rm -rf node_modules
        npm install
        zip -r handler.zip index.js lib node_modules
    

    and a deploy target that would package your code (upload code to s3) and deploy cloudformation.

    The package command is responsible for uploading the zip artifact specified in CodeUri and replace it with s3 URL in the sam.out.yaml

    deploy:
        aws cloudformation package \
            --template-file sam.yaml \
            --output-template-file sam.out.yaml \
            --s3-bucket my-artifact-bucket-name
    
        aws cloudformation deploy \
            --template-file sam.out.yaml
    

    Since you decided to have multiple lambdas in a single repository probably you would have two build commands for each lambda function and some cd ... logic to change working directory per function