Search code examples
node.jsaws-lambdaaws-sdk-js

Temporarily switch AWS credentials while using AWS JavaScript SDK


I am writing an API which runs on AWS Lambda in the Node environment.

My intention is to take a set of AWS credentials and create an S3 bucket in that AWS account. The issue is that requires me to "switch" AWS credentials from what my API is running with to what was passed in.

Looking online, I saw that the AWS Python SDK, boto3, actually enables you to pass a set of credentials when initializing the S3 client, but I saw no analogous concept in the JavaScript SDK for AWS.

However, I was able to create the following code that sort of accomplished the effect I desired:

    const {accessKeyId, secretAccessKey} = AWS.config;

    // Switch to their credentials
    AWS.config.update({
        accessKeyId: env.awsAccessKey,
        secretAccessKey: env.awsSecretKey
    });

    // Create the bucket in their AWS account (not ours)
    const client = new AWS.S3();

    await client.createBucket({
        Bucket: env.rootBucket
    }).promise();

    // Switch credentials back
    AWS.config.update({
        accessKeyId,
        secretAccessKey
    });

The problem I'm having is that when I run this global update to the AWS.config, other calls in my API are obviously affected - and that's not the intended behavior. Is there any way to accomplish what I want in the AWS JS SDK without doing this?

Any help would be appreciated.

Thanks!


Solution

  • Create multiple S3 client objects, each representing a different set of credentials (and/or different regions). If your compute is running with an IAM role then just use the default S3 client constructor to use those credentials. To target other credentials/regions, create an S3 client object specific to that use case.

    For example:

    const s3_local = new AWS.S3(); // default credentials provider hierarchy
    const s3_remote = new AWS.S3({accessKeyId: akid, secretAccessKey: skid});