Search code examples
amazon-web-servicesaws-lambdaamazon-dynamodbaws-sam-cli

AWS SAM CLI cannot access Dynamo DB when function is invoked locally


I am building an AWS lambda with aws-sam-cli. In the function, I want to access a certain DynamoDB table. My issue is that the function comes back with this error when I invoke it locally with the sam local invoke command: ResourceNotFoundException: Requested resource not found

const axios = require('axios')
const AWS = require('aws-sdk')
AWS.config.update({region: <MY REGION>})
const dynamo = new AWS.DynamoDB.DocumentClient()

exports.handler = async (event) => {
  const scanParams = {
    TableName: 'example-table'
  }
  const scanResult = await dynamo.scan(scanParams).promise().catch((error) => {
    console.log(`Scan error: ${error}`)
    // => Scan error: ResourceNotFoundException: Requested resource not found
  })

  console.log(scanResult)
}

However, if I actually sam deploy it to AWS and test it in the actual Lambda console, it logs the table info correctly.

{
  Items: <TABLE ITEMS>,
  Count: 1,
  ScannedCount: 1
}

Is this expected behavior? Or is there some additional configuration I need to do for it to work locally? My template.yaml looks like this:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: 'Example SAM stack'
Resources:
  ExampleFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs12.x
      Policies:
      - DynamoDBCrudPolicy:
          TableName: 'example-table'

Solution

  • I believe when you invoke your Lambda locally, SAM is not recognising which profile to use for the remote resources, ex: DynamoDB

    Try to pass the credentials profile for your remote dynamoDB

    ex:

    sam local invoke --profile default
    

    You can check the command documentation here: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html