95

When I am trying to load AWS credentials in my project it gives back an error.

When using credentials in plain text everything works good but when I am trying to use environment variables it's not working.

Error message. :

Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1

Here is my tried code :

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


const SESConfig = {
    apiVersion: "2010-12-01",
    accessKeyId: process.env.AWS_SECRET_KEY,
    accessSecretKey: process.env.AWS_SECRET_KEY,
    region: "us-east-1"
}
AWS.config.update(SESConfig);
var sns = new AWS.SNS()
var sns = new AWS.SNS();

function sendSMS(to_number, message, cb) {

    sns.publish({
        Message: message,
        Subject: 'Admin',
        PhoneNumber:to_number
    }, cb);
  
  }
  
  // Example
  const PhoneNumberArray = ['any mobile number']
  PhoneNumberArray.forEach(number => {
    sendSMS(number, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", (err, result)=>{
        console.log("RESULTS: ",err,result)
      })
  })
 
Yohan W. Dunon
  • 502
  • 10
  • 18
singh singh
  • 963
  • 1
  • 6
  • 10

16 Answers16

73

By default, the SDK detects AWS credentials set in your environment and uses them to sign requests to AWS. That way you don’t need to manage credentials in your applications.

Unix:

$ export AWS_ACCESS_KEY_ID="your_key_id"
$ export AWS_SECRET_ACCESS_KEY="your_secret_key"

Windows:

SET AWS_ACCESS_KEY_ID="your_key_id"
SET AWS_SECRET_ACCESS_KEY="your_secret_key"

Powershell:

$Env:AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
$Env:AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"

you can also add $ export AWS_SESSION_TOKEN='your_token' (optional)

See aws-sdk for more details.


Otherwise you can create a ~/.aws/credentials file and add:

[default]
aws_access_key_id = <YOUR_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>

See aws for more details.

GwenM
  • 1,198
  • 10
  • 24
26

I noticed that you are setting your accessKeyId and secretAccessKey to the same environment variable.

const SESConfig = {
    apiVersion: "2010-12-01",
    accessKeyId: process.env.AWS_SECRET_KEY,      // should be:  process.env.AWS_ACCESS_ID
    secretAccessKey: process.env.AWS_SECRET_KEY,  
    region: "us-east-1"
}

These are supplied as separate values by aws and should be represented by two separate environment variables. Maybe this is your issue?

GwenM
  • 1,198
  • 10
  • 24
GatesKennedy
  • 675
  • 4
  • 11
13

You can try create an AWS_PROFILE with the credentials if you have the AWS CLI installed.

$ aws configure --profile testuser
  AWS Access Key ID [None]: 1234
  AWS Secret Access Key [None]: 1234
  Default region name [None]: us-east-1
  Default output format [None]: text

After that you can set the AWS_PROFILE as environment variable.

Linux / Mac

export AWS_PROFILE=testuser

Windows

setx AWS_PROFILE testuser

After that you should be able to run your program and AWS will get the credentials from your profile. This way you don't have to save your credentials in .ENV. If you do, remember to add it in .gitignore.

https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html

https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

John Gherga
  • 399
  • 3
  • 8
11

Install dotenv

npm install dotenv --save

Create a .env file and add your Variables

AWS_ACCESS_KEY=1234567890
AWS_SECRET_KEY=XXXXXXXXXXXXXXXXXXX

Load dotenv in your project

require('dotenv').config();

Complete code

require('dotenv').config();
const AWS = require('aws-sdk');
const SESConfig = {
    apiVersion: "2010-12-01",
    accessKeyId: process.env.AWS_ACCESS_KEY,
    accessSecretKey: process.env.AWS_SECRET_KEY,
    region: "us-east-1"
}
AWS.config.update(SESConfig);
var sns = new AWS.SNS();

function sendSMS(to_number, message, cb) {

    sns.publish({
        Message: message,
        Subject: 'Admin',
        PhoneNumber:to_number
    }, cb);

  }

  const PhoneNumberArray = ['any mobile number']
  PhoneNumberArray.forEach(number => {
    sendSMS(number, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", (err, result)=>{
        console.log("RESULTS: ",err,result)
      })
  })
diegofcornejo
  • 301
  • 1
  • 6
8

I was able to fix this problem by specifying an apiVersion

AWS.config.update({
  region: 'MY_REGION',
  apiVersion: 'latest',
  credentials: {
    accessKeyId: 'MY_ACCESS_KEY',
    secretAccessKey: 'MY_SECRET_KEY'
  }
})
jeninja
  • 788
  • 1
  • 13
  • 27
5

worked after i followed the exact names from aws guide for the env vars

https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/loading-node-credentials-environment.html

AWS_ACCESS_KEY_ID  
AWS_SECRET_ACCESS_KEY  
AWS_SESSION_TOKEN (Optional)  
wly185
  • 129
  • 2
  • 3
  • This solved my problem.Thanks.But when i refresh the node server,aws is always running why? And after i hit the image and others unused document are also saved along with image.How to get rid of those documents and get rid of always running aws server in terminal? – Dulal Sandip Sep 27 '21 at 13:41
2

Note that the variable names in ~/.aws/credentials are case sensitive. That was what caused my problem

1

You can simply load the credentials through a dedicated config.json file.

{
    "accessKeyId": "<YOUR_ACCESS_KEY_ID>", 
    "secretAccessKey": "<YOUR_SECRET_ACCESS_KEY>", 
    "region": "eu-west-3"
}

Then use the AWS load command

AWS.config.loadFromPath('./config.json');

In this case you wouldn't need to update the AWS config AWS.config.update(...); as it is done right from the gecko.

Note that:

Loading credentials from a JSON document is not supported in browser scripts.

amarinediary
  • 4,930
  • 4
  • 27
  • 45
1

I have stored all the credentials in my config file itself. For windows, I got it solved by adding a Environment Variable to my nodejs application in .env.local

AWS_SDK_LOAD_CONFIG=1
Abinash
  • 466
  • 7
  • 15
0

I came across a similar problem, so I watched a few videos and read a bunch of documentation, In dotenv file try creating the IAM user that you wish to give permission to access the accountAWS_PROFILE="exampleProfile" this should be the same user that you got your Access key and secret from, then require so it should look something like this.

const SESConfig = {
   apiVersion: "2010-12-01",
   profile:process.env.AWS_PROFILE,
   accessKeyId: process.env.AWS_ACCESS_KEY,
   accessSecretKey: process.env.AWS_SECRET_KEY,
   region: "us-east-1"
}
Stefano Sansone
  • 2,377
  • 7
  • 20
  • 39
0

I switched to a prod role according to this https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-cli.html#switch-role-cli-scenario-prod-env

where there wasn't a 'prod' entry in my ~/.aws/credentials file

I got my sdk calls in my script working by calling

export AWS_SDK_LOAD_CONFIG=1

before runningg it

Mayowa Daniel
  • 397
  • 5
  • 14
0

I encountered the same issue but in my case, I was forced to authenticate through GSuite. That's because, in my work environment, GSuite (from Google) is the Single Sign-On (SSO) provider. I noticed that while a CLI command like:

aws s3 ls
worked as expected, the node.js code threw the error discussed in this article.

There are two solutions that work in my case:

  1. Add the relevant lines into the code from the sample below:

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

const s3 = new AWS.S3();

const credentials = new AWS.SharedIniFileCredentials({ profile: '<your_profile_name>' });

AWS.config.credentials = credentials;
AWS.config.region = '<your_region>';
const s3 = new AWS.S3({ region: '<your_region>' });

(async () => {
    await s3.putObject({
        Body: 'Hello World', 
      Bucket: "<your_bucket_name>", 
      Key: "my-file.txt"
    }, function (err, data){
        if (err) console.log(err, err.stack);
        else console.log(data);
    });
})()
  1. The second solution that also worked was using the proper environment variable. On my macOS, I had set the environment variable incorrectly as:

AWS_DEFAULT_PROFILE=<your_profile>

But when I set the below environment variable, my code worked like a charm:

AWS_PROFILE=<your_profile>

Refer to this article by AWS on environment variables: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html

Hope my solution helps.

0

Different situation I was in, but that was leading to the same error. I was using a snippet from the example code for a Pinpoint Push Notification Lambda, and it included these lines:

  // Specify that you're using a shared credentials file, and specify the
  // IAM profile to use.
  var credentials = new AWS.SharedIniFileCredentials({ profile: '...' });
  AWS.config.credentials = credentials;

I was using this code in my own Amplify CLI generated PushNotification Function. There were no issues when working with the Function on its own.

When I tried to call the PushNotification Function from another resource, I got that same error:

Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1

The solution for me was to simply remove the SharedIniFileCredentials code from the function entirely.

I presume this works because the Amplify environment is all managed, so that explicit AWS.config.credentials was redundant, as well as broken when running in certain scenarios.

Hope this helps anybody who is having a similar problem with calling Functions from other Function in an Amplify project! – I know that's not best practice, as discussed in this other stack overflow, but it works

Crayon
  • 46
  • 5
0

The problem is probably simply just that you're not running 'amplify init' in the same folder which has your config file.

I added a .env file to my root mobile app folder which simply said:

AWS_ACCESS_KEY_ID= "XXXXXXXXXXXXX"
AWS_SECRET_ACCESS_KEY=  "XXXXXXXXXXXXXXXXXX"

I also ran 'npm i dotenv' (Not sure if necessary)

And then I just had to run amplify init in the backend/server folder that had the .env file and not the frontend or mobile folder.

(sudo amplify init if you're using Mac)

It automatically detects your config based on a .env file in the same folder that you're running the command from.

You have to do all this from your frontend root folder I think or else it doesn't detect aws-config

Ahmedakhtar11
  • 1,076
  • 11
  • 7
0

I got this exact message in Google Chrome web browser after clicking on the "Launch Studio" button for my AWS Amplify app that I was viewing in the AWS web console. I was logged into AWS with my admin account and my Amplify app is deployed. Several minutes later I clicked that same "Launch Studio" button and it worked. I did not do anything but google for answers (which is how I got to this SO page).

botanyhelp
  • 153
  • 1
  • 1
  • 5
0

Using cdk-sso-sync worked for me.

"start": "ts-node ./src",
"dev": "cdk-sso-sync dev && export AWS_PROFILE=dev && yarn start"
Lucas Brogni
  • 129
  • 6