amazon-web-servicesaws-lambdaaws-codepipelineaws-codecommit

How to setup automated deployment from CodeCommit to a Lambda Function?


I'm trying to setup automated deployment of the contents ofa CodeCommit repository to a Lambda function (not an application). In this particular case it's a simple copy/paste from source to destination, there are no specific instructions regarding package installations.

I'm struggling to find a solution that doesn't involve setting up another Lambda function to handle this task. From what I understand, there is a solution using AWS' services CodeBuild and CloudFormation.

Does anyone have a solution for this? Alternatively, can you point to any good documentation?

P.S:

I found this question that seems to answer my question but the links in the relevant answer are outdated.


Solution

  • This is the solution that worked for me.

    I setup a pipeline with CodeCommit as source and a Build Phase (no Deploy Phase).

    The Build phase reads a buildspec.yml file which itself reads SAM template called template.yml. The SAM stack is created via CloudFormation.

    I created an s3 bucket to hold the build artifacts.

    Here is the sample buildspec.yml file:

    version: 0.2
    
    phases:
      install:
        commands:
          - echo Nothing to do in the install phase...
      pre_build:
        commands:
          - echo Nothing to do in the pre_build phase...
      build:
        commands:
        - aws cloudformation package --template-file template.yml 
                                      --s3-bucket <bucketname>
                                      --output-template-file newtemplate.yml
        - aws cloudformation deploy --stack-name <stackname>
                                    --capabilities CAPABILITY_IAM
                                    --template-file newtemplate.yml
                                    --role-arn arn:aws:iam::<account number>:role/CloudFormationServiceRole
      post_build:
        commands:
          - echo Build completed
    

    Here is the sample template.yml file :

    AWSTemplateFormatVersion : '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: CloudFormation Stack for the lambda function
    
    Resources:
    # Details about the Lambda function
      <StackName>:
        Type: AWS::Serverless::Function
        Properties:
          Handler: index.handler
          Runtime: nodejs12.x
          CodeUri: src/
    # Creates an alias named "live" for the function, and automatically publishes when you update the function.
          AutoPublishAlias: live
          DeploymentPreference:
    # Specifies the deployment configuration
              Type: AllAtOnce
    

    The file structure is :

    .
    ├── src/
    │   ├── node_modules/
    │   └── index.js
    ├── builspec.yml
    └── template.yml
    

    Make sure you set the correct IAM policies for the CloudFormation and CodeBuild IAMs.