Create AWS Lambda function to get Users from IAM

假装没事ソ 提交于 2021-01-29 04:44:33

问题


I want to get user details from AWS IAM so I have created a lambda function but there is an error with response code 502. My code is as below.

var AWS = require('aws-sdk');
var iam = new AWS.IAM();
AWS.config.loadFromPath('./config.json');

let getUsers = async (event, callback) => {
    var params = {
        UserName: "5dc6f49d50498e2907f8ee69"
    };

    iam.getUser(params, (err, data) => {
        if (err) {
            callback(err)
        } else {
            console.log(data)
            callback(data)
        }
    })
};

回答1:


Since your function already is async you don't need to use the old, outdated callback approach.

The AWS SDK methods provide a .promise() method which you can append to every AWS asynchronous call and, with async, you can simply await on a Promise.

    var AWS = require('aws-sdk');
    var iam = new AWS.IAM();
    AWS.config.loadFromPath('./config.json');

    let getUsers = async event => {
        var params = {
            UserName: "5dc6f49d50498e2907f8ee69"
        };

        const user = await iam.getUser(params).promise()
        console.log(user)
    };

Hopefully you have a handler that invokes this code, otherwise this is not going to work. If you want to export getUsers as your handler function, make sure export it through module.exports first. I.e: module.exports.getUsers = async event.... Double check that your Lambda handler is properly configured on the function itself, where index.getUsers would stand for index being the filename (index.js) and getUsers your exported function.



来源:https://stackoverflow.com/questions/59044712/create-aws-lambda-function-to-get-users-from-iam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!