20

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).

7 Answers 7

26

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.

1
  • 1
    I like this as it is platform independent, not relying on EC2 metadata or Lambda context, so I can use it during development or for code which is always run outside of AWS. Jul 31, 2019 at 12:30
9

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);
})();
1
  • best up to date answer
    – Shraneid
    Mar 3, 2022 at 18:36
7

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]);
};
1
  • 3
    And how you get the context? I think you are only dealing with the problem within a lambda.
    – Raul Guiu
    Feb 19, 2020 at 16:36
3

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]);
});
1

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);
};
0

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.

0

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);
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.