Search code examples
amazon-web-servicesaws-lambdaamazon-iamaws-sdk-jsaws-sdk-nodejs

AWS SDK - Writing a lambda to get all roles for the current account


Working on writing a lambda to get all IAM roles within the current account using the AWS SDK documentation provided for Javascript: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html

However, my lambda keeps returning a null value, whereas I'm expecting it to return a list of existing roles in the response body:

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

exports.handler = async (event) => {
    var iam = new AWS.IAM();

    var roles = [];
    iam.listRoles(function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else roles.push(data);           // successful response
        const response = {
          statusCode: 200,
          body: JSON.stringify(roles)
      };
      return response;
    });
 
};

I'm obviously missing something here. Any insights would be appreciated.


Solution

  • You are using an Old version of the AWS SDK for JavaScript. That doc you referenced is not the latest.

    Try using the latest version as described in this AWS SDK for JavaScript DEV Guide V3 here:

    https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html