How to avoid setting aws config as env variable externally while using dynamoose.js

1.5k views Asked by At

My aws config doesn't work unless I set it externally through env variable

db connection works only if I set the credentials externally like,

export AWS_ACCESS_KEY_ID=abcde
export AWS_SECRET_ACCESS_KEY=abcde
export AWS_REGION=ap-south-1
export AWS_DYNAMODB_ENDPOINT="http://localhost:8000"

It doesn't work if I don't set these externally. For example if I set it in code like the following, it does not work.

dynamoose.AWS.config.update({
  accessKeyId:'abcde',
  secretAccessKey:'abcde',
  region:'ap-south-1',
  endpoint:'http://localhost:8000'
});

I don't want to set config in any variable externally. Is there a way to just manage this in nodejs code?

These are the alternates I have tried/considered

  1. Setting env variable in the code, this doesn't work either

    process.env.AWS_REGION='ap-south-1';

  2. I read about dotenv package. But it is recommended that it should be used for dev only and not production (I am not sure if that will work)

Please help me resolve this. How do I manage the config in code only?

2

There are 2 answers

5
Charlie Fish On

The problem is probably that you are creating or requiring your Dynamoose models before you run the dynamoose.AWS.config.update method.

Make sure that dynamoose.AWS.config.update is the very first method you call, and you haven't created or initialized any Dynamoose related things before.

For example.

const dynamoose = require('dynamoose');
dynamoose.AWS.config.update({
  accessKeyId:'abcde',
  secretAccessKey:'abcde',
  region:'ap-south-1',
  endpoint:'http://localhost:8000'
});
const Model = require('./models/MyModel'); // should happen after `dynamoose.AWS.config.update`

Another trick I would try to do is enable debug logging and go through the logs to see what is happening. You can enable Dynamoose logging by running export DEBUG=dynamoose*, then rerunning the script.

0
Traycho Ivanov On

If you are working with newer version syntax is changed and could be find here .

https://dynamoosejs.com/guide/Dynamoose/#dynamooseawssdk

const sdk = dynamoose.aws.sdk; // require("aws-sdk");
sdk.config.update({
    "accessKeyId": "AKID",
    "secretAccessKey": "SECRET",
    "region": "us-east-1"
});