Error loading JSON credentials with AWS SDK results

I am trying to load credentials for AWS using loadFromPath and get an unexpected error. Hardcoding with the same credentials with AWS.config.update works fine. To make sure that the path and format of the credential file is correct, I downloaded the same with fs.readFile and it loads correctly, so there are no problems with access rights / permissions. It seems super basic, but I pulled my hair, trying to solve. Thank you for your help.

Error / Output:

Here: /home/ec2-user/.ec2/credentials.json Got this through readFile: { access_id: 'XXXXXXX', private_key: 'XXXXXXX', keypair: 'praneethkey', 'key-pair-file': '/home/ec2-user/.ec2/praneethkey.pem', region: 'us-west-2' } /home/ec2-user/node_modules/aws-sdk/lib/config.js:221 if (err) throw err; ^ SyntaxError: Unexpected token < at Object.parse (native) at /home/ec2-user/node_modules/aws-sdk/lib/metadata_service.js:100:38 at IncomingMessage.<anonymous> (/home/ec2-user/node_modules/aws-sdk/lib/metadata_service.js:75:43) at IncomingMessage.EventEmitter.emit (events.js:117:20) at _stream_readable.js:910:16 at process._tickCallback (node.js:415:13) 

Code:

 'use strict'; var AWS = require('aws-sdk'); var fs = require('fs'); var pathv = process.env.HOME + '/.ec2/credentials.json'; AWS.config.loadFromPath(pathv); console.log('Here: ' + pathv); fs.readFile(pathv, 'utf8', function (err, data) { if (err) { console.log('Error: ' + err); return; } data = JSON.parse(data); console.log("Got this through readFile:",data); 
+6
source share
2 answers

You can skip credential configuration if you have env vars AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
The AWS SDK will read these vars by default.

If you still want to load the credentials from the file, check that credentials.json has valid JSON.

Regarding http://aws.amazon.com/sdkfornodejs/ there should be something like

 { "accessKeyId": "akid", "secretAccessKey": "secret", "region": "us-west-2" } 

It looks like you have access_id where it should be "accessKeyId" and private_key where it should be "secretAccessKey"

+9
source

Found the answer to this question. For some bizarre reason, Amazon uses different field names for credentials in Node compared to other frameworks (like Ruby).

There are only two first elements in Ruby:

 "access_id": "[Your AWS Access Key ID]", "private_key": "[Your AWS Secret Access Key]", 

In Node.js, these are the same elements:

 "accessKeyId": "[Your AWS Access Key ID]", "secretAccessKey": "[Your AWS Secret Access Key]", 

The names in the JSON credentials were changed for the latter and the error disappeared. Why can't it be the same?

0
source

Source: https://habr.com/ru/post/951360/


All Articles