CCCC
CCCC

Reputation: 6471

How to handle lambda function re-deploy when the dynamodb table name change

Let's say I've created a dynamnodb Table called "myTable".

I have many lambda functions which access "myTable"

This is one of the example function.

'use strict'
const AWS = require('aws-sdk');
const sha1 = require('sha1');
const moment = require('moment');

exports.handler = async function (event, context, callback) {
    const documentClient = new AWS.DynamoDB.DocumentClient();

    let responseBody = "";
    let statusCode = 0;

    const { url } = JSON.parse(event.body);

    let id = sha1(Buffer.from(new Date().toString())) ;
    const params = {
        TableName : "myTable", //line a
        Item: {
            id: id,
            url: url,
        }
    };

    try{
        const data = await documentClient.put(params).promise();
        responseBody = JSON.stringify(data);
        statusCode = 201;
    }catch(err){
        responseBody = `Unable to create users: ${err}`;
        statusCode = 403;
    }

    const response = {
        statusCode: statusCode,
        headers:{
            "Content-Type": "application/json",
            "access-control-allow-origin": "*"
        },
        body: responseBody
    }

    return response
}

However, if I want to change the Table name, it causes some problems.

  1. I need to delete "myTable" in dynamodb manually first, and then run update-stack for updated template.
  2. I need to modify line a in above code for all of my lambda function, and then I need to upload the new zip files to s3 bucket for the functions.

Is there any convenient way to handle these 2 problems?

Upvotes: 1

Views: 218

Answers (2)

Marcin
Marcin

Reputation: 238637

  1. I need to delete "myTable" in dynamodb manually first, and then run update-stack for updated template.

If all is managed by CloudFormation (CFN), you don't need nor should delete anything "manually". Its a bad practice to manually modify/delete resources managed by CloudFormation.

  1. I need to modify line a in above code for all of my lambda function, and then I need to upload the new zip files to s3 bucket for the functions.

Normally you would not hard-code your table name like this. A common way is to pass the template name through lambda environment variables. If all is managed by CFN, all updates should be done automatically for your by CFN.

Upvotes: 1

Praveen Sripati
Praveen Sripati

Reputation: 33545

For automating such tasks look at CICD tools. Spinaker is one of it. There is no need to reinvent the tools again.

Upvotes: 1

Related Questions