Step by Step instruction for AWS Lambda with dynamodb using cloudformation template
Tags: awslambda, dynamodb, cloudformation, aws
Published: 2024-02-04 14:28:38

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')
        }
```

```
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

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ppdgx924808ud4d30ks3.png)
Step 2: Cloudformation will be three resource created 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9lfe49da7h46ppjscu1.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n2h66dl9gwyeor0wfho5.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0yu99ja3zp9jm2ir37v.png)

Step 5: Clean AWS Resource using cloudformation template 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hmlxrv2jg1lc61wx6zh.png)


Please github source code : [Click Here](https://github.com/jaganrajagopal/cloudformationtemplate.git)

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