I'm trying to get AWS IAM Arn user using STS GetCallerIdentity API Amazon provided. The code below basically logs the correct data in the console. However, i want to return the data as a string/json and I can't seem to return the value because it's inside a parameter.
How can I return the information I need that's in the data
callback?
Any tips/advice would be very much appreciated!!
export function GetIamUser() {
const sts = new AWS.STS();
sts.getCallerIdentity({}, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
}
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/STS.html#getCallerIdentity-property
This is the output when I run the method above
data = {
Account: "123456789012",
Arn: "arn:aws:iam::123456789012:user/user",
UserId: "AKIAI44QH8DHBEXAMPLE"
}
UPDATE: I've tried returning the function callback by the method below, however the value keeps returning undefined
export function GetArnUser() {
var user;
sts.getCallerIdentity({}, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
user = data.Arn;
});
return user;
}
This is an async issue. you are using callbacks, which means you need to pass a callback function to GetArnUser()
, similar to the below
export function GetArnUser(cb) {
var user;
sts.getCallerIdentity({}, function (err, data) {
if (err) console.log(err, err.stack);
else {
console.log(data);
user = data.Arn;
cb(user)
}
});
}