Share Config Properties between Serverless Config and Lambda Functions

Image for post
Image for post
Photo by Dan Farrell on Unsplash

The Problem

The Solution

// constants.json
{ "dynamoTableName": "myTable" }

// lambda.js
const { dynamoTableName } = require('./constants');

const AWS = require('aws-sdk');

module.exports.getAllRecords = (event, context, callback) => {
const dynamo = new AWS.DynamoDB.DocumentClient();
const params = { TableName: dynamoTableName };
dynamo.scan(params, (error, data) => {
...

// serverless.yml
service: my-service

custom:
dynamoTableName: ${file(./constants.json):dynamoTableName}

provider:
name: aws
runtime: nodejs12.x

iamRoleStatements:
- Effect: 'Allow'
Action:
- 'dynamodb:*'
Resource:
Fn::Join:
- ':'
- - 'arn:aws:dynamodb'
- 'Ref': 'AWS::Region'
- 'Ref': 'AWS::AccountId'
- 'table/${self:custom.dynamoTableName}'

resources:
Resources:
MyDynamo:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:custom.dynamoTableName}

functions:
...

Software engineer crafting full-stack, cloud-native solutions for enterprise

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store