Tuesday, March 7, 2017

[Quick Tip] AWS SDK: Get Account Number

I ran into an issue the other day, where I was looking to determine which account I was in on AWS. Since we are primarily trying to work with Javascript on the project. I decided to do this one in Javascript as well.

Code:

var iam = new AWS.IAM();

iam.getUser(null,function(err,data){
    output = data['User'].Arn.match(/arn\:aws\:iam\:\:(\d{12})\:user\/.*/i);
    console.log(output[1]);
});

Obviously you can just log it out, but you can also use it for more practical purposes, such as verifying which account you're in before doing something important. In my case I using for some automated scripts so that they determine what they are going to do based on which account they are using at the time. Preventing certain actions.



References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getUser-property

No comments: