Allloush
Allloush

Reputation: 1168

AWS JS SDK doesn't Loading Credentials from environment variables

I configured .env file to have AWS credentials, it doesn't work.

in the docs, it is written the config will automatically be loaded from .env file. but it doesn't.

I tried to add the following

    aws.config.update({
    region: process.env.AWS_region,
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});

and that worked.

any idea why AWS SDK doesn't load the options automatically?

"aws-sdk": "^2.288.0",
"dotenv": "^6.0.0",

Upvotes: 8

Views: 6287

Answers (3)

noobDev
noobDev

Reputation: 1

couldn't find an answer to help me, but I ran into an issue where AWS was not loading from dotenv where AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY were not loading from Dotenv. (using AWS SDK 3.0 for node/JS)

Dotenv does not by default overwrite any variables that are already set when it is loaded: https://www.npmjs.com/package/dotenv#-faq. See question: What happens to environment variables that were already set?

So.. to get dotenv to overwrite any values that may be existing, just add the override:true value when you import dotenv - i.e. require('dotenv').config({override:true}).

Then use the fromEnv method in @aws-sdk/credential-providers to load from your .env file: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-credential-providers/#fromenv

Anyway, I'm not a professional developer, just someone figuring things out as I go. Hope this helps other people though.

Upvotes: 0

Mark Smithson
Mark Smithson

Reputation: 61

Old question, but answering as I had this issue with a test.

This is due to the AWS SDK capturing the credentials when the sdk is first required or imported.

When you run dotenv.config(), it has already completed this and does not re-read the environment variables.

Updating the AWS config yourself sets the values and is a reasonable solution.

Upvotes: 6

juve stig
juve stig

Reputation: 31

I had the same issue and then figured that I had to export the env variables in the shell profile (~/.zshrc in my case zsh - just add export AWS_ACCESS_KEY_ID=<key> and the same for other AWS vars ). Restarted the terminal console and then my node aws sdk was able to pick it up. If you are using node aws sdk, then I'd suggest print process.env.AWS_ACCESS_KEY_ID in your code to verify that your node code is indeed able to read the env variable in the first place. Hope that helps.

Upvotes: 2

Related Questions