How do I find my AWS account ID using JavaScript/NodeJS?
Should work when explicitly providing keys for a root-account or IAM user. Should also work when invoked inside of an ec2-instance which is configured with instance-profile (no keys).
The best way is via "Security Token Service":
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./config.json');
var sts = new AWS.STS();
sts.getCallerIdentity({}, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log(JSON.stringify(data.Account));
}
});
This would print the account ID with a simple call.
Just building on @Facundo Victor's excellent answer... This is what I'm using a few years later refactored as ES6:
// See https://github.com/aws/aws-sdk-js/pull/1391
process.env.AWS_SDK_LOAD_CONFIG = 1;
const { config, STS } = require('aws-sdk');
(async () => {
const sts = new STS();
// See https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-promises.html
const { Account: account} = await sts.getCallerIdentity({}).promise();
const { region } = config;
console.log(account, region);
})();
The easiest way I find is to pull the account ID from the context data:
exports.handler = async (event, context) => {
// Log the invoked function ARN and split to get Account ID
console.log(JSON.stringify(context.invokedFunctionArn).split(':')[4]);
};
The following snippet will print the account ID using nodejs and latest aws-sdk:
var AWS = require('aws-sdk');
var iam = new AWS.IAM();
var metadata = new AWS.MetadataService()
var _ = iam.getUser({}, (err, data) => {
if (err)
metadata.request('/latest/meta-data/iam/info/', (err, data) => {
if (err) console.log(err, err.stack);
else console.log(JSON.parse(data).InstanceProfileArn.split(':')[4]);
});
else
console.log(data.User.Arn.split(':')[4]);
});
If you also require the Account Alias (i.e. the name you gave to your account), you would use IAM's SDK. With an Account Alias, you know exactly which account it is that invoked your code. An Account ID is less descriptive.
AWS IAM SDK: listAccountAliases()
Below is code for your lambda:
const AWS = require('aws-sdk');
const iam = new AWS.IAM();
exports.handler = async (event) => {
let accountAliases = await iam.listAccountAliases({}).promise();
console.log(accountAliases);
};
For those using Typescript, here's a slight variation of Andrew's answer:
function getCallerAccountNum() : Promise<string>{
const sts = new STS()
return sts.getCallerIdentity({}).promise()
.then(
({ Account: accountNum}) => accountNum ??
Promise.reject("Error retrieving account number")
)
}
The addition I made was to check for an undefined
account number via the nullish coalescing operator, and in that case to reject the promise with a custom message.
This is based on previous answers, but using TypeScript and the newer aws-sdk v3.
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
export const getAWSAccountId = async (): Promise<string> => {
const response = await new STSClient({}).send(
new GetCallerIdentityCommand({}),
);
return String(response.Account);
};