Finding AWS Account ID Using JavaScript

How to find AWS account ID using JavaScript / NodeJS?

It should work if you explicitly specify the keys for the root account user or IAM user. It should also work when called inside an ec2 instance that is configured with an instance profile (without keys).

+7
amazon-ec2
source share
2 answers

The best way is through the 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 will output the account id with a simple call.

+3
source share

The following snippet will print the account id using nodejs and the 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]); }); 
+2
source share

All Articles