Now that we have made changes to the Lambda function, let’s try to add a table to this application.
In the Cloud9 file navigation pane on the left hand side, open the api/template.yaml file.
Add the following section in the Resources section. Note: please adhere to proper identation. YAML, by design works based on indentation.
ServerlessTable:
Type: AWS::Serverless::SimpleTable
Properties:
Tags:
Name: api
Now add the DynamoDB CRUD policy to the Lambda function. Please add the following underneath the HelloWorldFunction resource, indented to Properties.
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref ServerlessTable
Now add the table name as the environment variable
Environment:
Variables:
TABLE_NAME: !Ref ServerlessTable
When you are done, your template will look like this:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
api
Sample SAM Template for api
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs14.x
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref ServerlessTable
Environment:
Variables:
TABLE_NAME: !Ref ServerlessTable
ServerlessTable:
Type: AWS::Serverless::SimpleTable
Properties:
Tags:
Name: api
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
Let’s build and deploy this by running the following commands:
sam build
sam deploy
If you look at the console output, you will see the changeset having a new DynamoDB table.
Next, let’s add a row each time we hit this endpoint.