问题
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