Finding my AWS account ID using JavaScript

可紊 提交于 2020-12-29 10:15:05

问题


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


回答1:


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.




回答2:


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



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



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



回答5:


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


来源:https://stackoverflow.com/questions/35563270/finding-my-aws-account-id-using-javascript

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