6

I am using Node with lambda and the AWS Javascript SDK. I have a role attached to the lambda function that allows the access I need to do. I want to be able to accept user input of access and secret keys and update my AWS config to perform new actions with those updated credentials. So far

let AWS = require("aws-sdk");  // I do the normal import 
let ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'});  // do some dynamo action 

....

Then use these keys that have rights to another accounts resources

AWS.config = new AWS.Config({
    accessKeyId: data.accessKey,
    secretAccessKey: data.secretAccessKey
}); 

When I perform a new task it just uses the permissions provided with the lambda role and not the updated AWS creds. Any ideas?

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
user2385520
  • 103
  • 1
  • 12
  • 2
    Try creating a new client AFTER you set those credentials (`let ddb2 = new AWS.DynamoDB(...`). – John Rotenstein Jun 22 '18 at 01:41
  • I just tried that and have the same issue. – user2385520 Jun 22 '18 at 01:42
  • Try passing the credentials directly to the DynamoDB client constructor like: `new AWS.DynamoDB({ accessKeyId: data.accessKey, secretAccessKey: data.secretAccessKey })`. Also make sure `data.accessKey` and `data.secretAccessKey` have the values you think they do during the execution of the Lambda function. If they aren't set correctly, then you are just passing `null` which would mean it would fall back to the Lambda execution role. – Mark B Jun 22 '18 at 14:26

1 Answers1

2

When you update the AWS.config, it updates the AWS object. Any AWS Service objects (S3, EC2, DynamoDB, ...) objects created since then will have the updated credentials. It will not update any service objects created before the update to AWS.config.

As AWS Guru @johnrotenstein suggested, you should create your service object after updating the config. If you ddb object is already created at this time, just redeclare it as a new DynamoDB({...})

const AWS = require('aws-sdk')
AWS.config = new AWS.Config({
    accessKeyId: data.accessKey,
    secretAccessKey: data.secretAccessKey
})
let ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'})

Another possibly simpler solution is to use the update method on the service object's config attribute as such:

const AWS = require('aws-sdk')
let ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'})
ddb.config.update({accessKeyId: '', secretAccessKey: ''})
// ddb will now use the new credentials for future calls
Tom Nijs
  • 3,835
  • 3
  • 22
  • 40
  • `AWS.config = new AWS.Config({ accessKeyId: data.accessKey, secretAccessKey: data.secretAccessKey })` this will globally set the access key and id and won't allow to use resources in same account. – Atul Kumar Jun 04 '19 at 21:19