Search code examples
javascriptnode.jsamazon-web-servicesaws-lambdaaws-sdk-js

Nodejs AWS Lambda switching to another accounts access and secret key to perform functions


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?


Solution

  • 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