Having trouble converting AWS node SDK v2 lambda to v3

0

A simple (and probably silly) question, but I can't see why the first code works using SDK V2, but the second using SDK V3 doesn't. Both are deployed in the same region, with the same IAM role and permissions.

'use strict';

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

exports.handler = async function(event, context, callback) {
        let output;

        try {
                let stsClient = new AWS.STS({ region: 'eu-west-1' });
                let response = await stsClient.getCallerIdentity({}).promise();
                output = { account: response.Account };
        }
        catch (e){
                output = { error:  e.message  };
        }

        let response = {
                statusCode: 200,
                headers: { "Content-type" : "application/json" },
                body: JSON.stringify(output)
        };

        return response;
};

The result is:

{
  "statusCode": 200,
  "headers": {
    "Content-type": "application/json"
  },
  "body": "{\"account\":\"98831xxxxxxxxx\"}"
}

Now the same code in version 3 (as far as I can make out):

'use strict';

const { STSClient, GetCallerIdentityCommand } = require('@aws-sdk/client-sts');

exports.handler = async function(event, context, callback) {
    let output;

    try {
        let stsClient = new STSClient({ region: 'eu-west-1' });
        const command = new GetCallerIdentityCommand({});
        const response = await stsClient.send(command);
        output = { account: response.Account };
    }
    catch (e){
        output = { error:  e.message };
    }

    let response = {
        statusCode: 200,
        headers: {  "Content-type" : "application/json"  },
        body: JSON.stringify(output)
    };

    return response;
};

And the result is:

{
  "statusCode": 200,
  "headers": {
    "Content-type": "application/json"
  },
  "body": "{\"error\":\"Could not load credentials from any providers\"}"
}

Any help appreciated :)

David

dmb0058
質問済み 10ヶ月前1459ビュー
1回答
0
承認された回答

The error message "Could not load credentials from any providers" typically indicates that the AWS SDK is unable to locate your AWS credentials.

In AWS SDK for JavaScript (v3), the default credential provider has been updated to be more strict than v2. It no longer includes the EC2 Instance Metadata Service (IMDS) by default. This could be the reason why your v3 code isn't working as expected.

To use the same default credential provider as v2, you can use the DefaultCredentialProvider from @aws-sdk/credential-provider-node package. Here's how you can modify your v3 code:

'use strict';

const { STSClient, GetCallerIdentityCommand } = require('@aws-sdk/client-sts');
const { defaultProvider } = require('@aws-sdk/credential-provider-node');

exports.handler = async function(event, context, callback) {
    let output;

    try {
        let stsClient = new STSClient({ 
            region: 'eu-west-1',
            credentials: defaultProvider() 
        });
        const command = new GetCallerIdentityCommand({});
        const response = await stsClient.send(command);
        output = { account: response.Account };
    }
    catch (e){
        output = { error:  e.message };
    }

    let response = {
        statusCode: 200,
        headers: {  "Content-type" : "application/json"  },
        body: JSON.stringify(output)
    };

    return response;
};

This code will use the defaultProvider as the credential provider, which includes the EC2 IMDS and should work as expected in a Lambda environment.

profile picture
回答済み 10ヶ月前
profile picture
エキスパート
レビュー済み 2ヶ月前
  • That's fantastic, exactly what I needed!

    Thanks so much for this, I suspected it might be something that had changed between versions or that had been a default in the v2 SDK but unbundled in v3.

    I suspect you saved me many hours of searching :)

    David

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ