DEV Community

Cover image for Step by Step instruction for AWS Lambda with dynamodb using cloudformation template
Jagan
Jagan

Posted on

Step by Step instruction for AWS Lambda with dynamodb using cloudformation template

To create a Python Lambda function that fetches employee information (employeeid and employeename) from a DynamoDB table, you'll need to write a Python script for the Lambda function and include it in your CloudFormation template. Here's an example setup:

Lambda Function (Python Script): This script uses the AWS SDK for Python (Boto3) to interact with DynamoDB.

CloudFormation Template: This template includes the Lambda function and necessary permissions.

First, here's the Python script for the Lambda function:
python code:

import json
import boto3
import os

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])

    try:
        # Assuming the event contains the employeeid
        employeeid = event['employeeid']
        response = table.get_item(
            Key={
                'employeeid': employeeid
            }
        )
        employee = response.get('Item', {})

        if not employee:
            return {'statusCode': 404, 'body': json.dumps('Employee not found.')}

        return {
            'statusCode': 200,
            'body': json.dumps(employee)
        }

    except Exception as e:
        print(e)
        return {
            'statusCode': 500,
            'body': json.dumps('Error fetching employee data')
        }
Enter fullscreen mode Exit fullscreen mode
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  EmployeeTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      TableName: EmployeeTable
      AttributeDefinitions:
        - AttributeName: employeeid
          AttributeType: S
      KeySchema:
        - AttributeName: employeeid
          KeyType: HASH
      BillingMode: PAY_PER_REQUEST

  EmployeeLambdaExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Policies:
        - PolicyName: LambdaDynamoDBAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - dynamodb:GetItem
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: '*'

  EmployeeFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: EmployeeFunction
      Runtime: python3.8
      Handler: index.lambda_handler
      Role: !GetAtt EmployeeLambdaExecutionRole.Arn
      Environment:
        Variables:
          DYNAMODB_TABLE: !Ref EmployeeTable
      Code:
        ZipFile: |
          <Your Lambda Function Python Code Here>

  # Add additional resources and outputs as needed

Enter fullscreen mode Exit fullscreen mode

Step 1: Please go to the AWS Cloudformation console and upload the code from local system

Image description
Step 2: Cloudformation will be three resource created

Image description

Step 3: AWS Lambda was created via AWS Cloudformation , please go to AWS Lambda function and open the code as mention in below

Image description

Step 4: IAM roles will be created and Dynamodb also will be created

Image description

Step 5: Clean AWS Resource using cloudformation template

Image description

Please github source code : Click Here

Please check more the articles : https://awstrainingwithjagan.com/aws-solution-architecture-cheat-sheets/

Top comments (0)