DEV Community

Tammura
Tammura

Posted on • Originally published at awstip.com on

Creating a AWSLambda triggered by a push on CodeCommit

Introduction

This tutorial explains how to create such a simple “infrastructure” that it could serve as a fun hello world for someone entering the DevOps world. However, as of 13/02/2024, it takes days of Google searching and hours of chatting with the new artificial intelligences that will conquer the world to accomplish this simple stack.

_In this article, we will only delve into creating the stack. To install SAM locally, refer to this [_article](https://aws.plainenglish.io/develop-aws-lambda-functions-locally-on-your-machine-ccdd37e10092)

Table of contents

Global Template Setup

Creating AWS Event Watcher

Creating AWS Lambda Function

Configuring Lambda Invocation Permission

Creating Event Role

Complete Template

Global Template Setup

The global setup of the template.yaml file should be as follows:

# template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: ''

Globals:
  Function:
    Timeout: 300
    MemorySize: 128

Resources:
  <List of Resources (Event, Lambda, Rule, etc.)>
Enter fullscreen mode Exit fullscreen mode

Creating AWS Event Watcher

The first step is to create the event that will trigger our function. This process requires configuring parameters such as the repository and event details:

MyEventRule: # Event name
  Type: AWS::Events::Rule
  Properties:
    EventPattern:
      source:
        - aws.codecommit # Event source type
      detail-type:
        - 'CodeCommit Repository State Change' # Event detail type, don't change it
      resources: # You can define multiple resources
        - <code_commit_repo_arn> # Code commit repository Arn
      detail:
        event:
          - referenceCreated
          - referenceUpdated
        referenceType:
          - branch # reference type can be multiple types (tag, commit etc.)
        referenceName:
          - master # branch name
    Targets:
      - Id: MyFunctionTrigger
        Arn: !GetAtt MyFunction.Arn # Lambda function arn
    RoleArn: !GetAtt MyEventRole.Arn # Event role arn
Enter fullscreen mode Exit fullscreen mode

Creating AWS Lambda Function

The second step is to create the function itself. This process involves configuring basic parameters such as runtime and policies, along with other parameters to add the event as a trigger for the function:

MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: src/ # Directory for app.py
    Handler: app.lambda_handler # Change if your main is another function instead lambda_handler
    Runtime: python3.11 # Python runtime
    Architectures:
      - x86_64
    Policies: # Add policies for your lambda, so you can access AWS services
      - AmazonS3ReadOnlyAccess
    Events: 
      MyEventRule: # Add event we just created
        Type: EventBridgeRule
        Properties:
          Pattern: 
              source: 
                  - !GetAtt MyEventRule.Arn # EventRule Arn
Enter fullscreen mode Exit fullscreen mode

Configuring Lambda Invocation Permission

The next two steps are to configure permissions to invoke the lambda. First, create an AWS::Lambda::Permission:

MyFunctionPermission:
  Type: AWS::Lambda::Permission
  Properties: 
    FunctionName: 
      !Ref MyFunction
    Action: "lambda:InvokeFunction" # Allowing to invoke lambda function
    Principal: "events.amazonaws.com"
    SourceArn: !GetAtt MyEventRule.Arn # Configure source arn that can invoke function
Enter fullscreen mode Exit fullscreen mode

Creating Event Role

The last step is to configure the event within which we define the event policies to trigger the lambda by creating an AWS::IAM::Role:

MyEventRole:
  Type: AWS::IAM::Role
  Properties:
    AssumeRolePolicyDocument:
      Version: 2012-10-17
      Statement:
        -
          Effect: Allow
          Principal:
            Service:
              - events.amazonaws.com
          Action: sts:AssumeRole
    Path: /
    Policies:
      -
        PolicyName: lambda-invoke
        PolicyDocument:
          Version: 2012-10-17
          Statement:
            -
              Effect: Allow
              Action: lambda:InvokeFunction
              Resource: !GetAtt MyFunction.Arn
Enter fullscreen mode Exit fullscreen mode

Complete Template

For convenience, here’s a copy of the complete template to facilitate the copy-paste process:

# Complete template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: ''

Globals:
  Function:
    Timeout: 300
    MemorySize: 128

Resources:
  MyEventRule: # Event name
    Type: AWS::Events::Rule
    Properties:
      EventPattern:
        source:
          - aws.codecommit # Event source type
        detail-type:
          - 'CodeCommit Repository State Change' # Event description
        resources: # You can define multiple resources
          - <code_commit_repo_arn> # Code commit repository Arn
        detail:
          event:
            - referenceCreated
            - referenceUpdated
          referenceType:
            - branch # reference type can be multiple types (tag, commit etc.)
          referenceName:
            - master # branch name
      Targets:
        - Id: MyFunctionTrigger
          Arn: !GetAtt MyFunction.Arn # Lambda function arn
      RoleArn: !GetAtt MyEventRole.Arn # Event role arn

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/ # Directory for app.py
      Handler: app.lambda_handler # Change if your main is another function instead lambda_handler
      Runtime: python3.11 # Python runtime
      Architectures:
        - x86_64
      Policies: # Add policies for your lambda, so you can access AWS services
        - AmazonS3ReadOnlyAccess
      Events: 
        MyEventRule: # Add event we just created
          Type: EventBridgeRule
          Properties:
            Pattern: 
                source: 
                    - !GetAtt MyEventRule.Arn # EventRule Arn

  MyFunctionPermission:
    Type: AWS::Lambda::Permission
    Properties: 
      FunctionName: 
        !Ref MyFunction
      Action: "lambda:InvokeFunction" # Allowing to invoke lambda function
      Principal: "events.amazonaws.com"
      SourceArn: !GetAtt MyEventRule.Arn # Configure source arn that can invoke function

  MyEventRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          -
            Effect: Allow
            Principal:
              Service:
                - events.amazonaws.com
            Action: sts:AssumeRole
      Path: /
      Policies:
        -
          PolicyName: lambda-invoke
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              -
                Effect: Allow
                Action: lambda:InvokeFunction
                Resource: !GetAtt MyFunction.Arn
Enter fullscreen mode Exit fullscreen mode

By following the steps outlined in this tutorial, you can automate tasks and streamline your development process with ease. Embrace the power of AWS Lambda and CodeCommit integration to unlock new efficiencies in your projects.

https://medium.com/media/591665aeb9cf0a86587c0ec5918108ff/href

Thank you for reading, and happy coding!


Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more