Retrieve AWS AccountID using PowerShell

As an AWS customer writing programs against AWS service APIs, using the AWS Tools for PowerShell, you’ll often need to reference your AWS AccountID. For example, some service API calls require passing in an Amazon Resource Name (ARN), which contains your AWS AccountID as one of its parts. Much of the time, you won’t have to manually construct an ARN, but in some cases, you’ll need to manually  construct an ARN.

On StackOverflow, one of the most popular Q&A sites on the Internet for developers, the suggestion to retrieve your AWS AccountID is to examine the OwnerID property of a default EC2 Security Group, in any supported AWS region. Although that may work, it might feel a little odd hitting the service APIs for EC2 Security Groups, simply to obtain your AWS AccountID.

As an alternative, consider using the AWS Security Token Service (STS). STS includes an API called GetCallerIdentity, which will return some basic details about the entity that’s calling it. You’ll receive your AWS AccountID as the “Account” property, the Identity & Access Management (IAM) identity’s ARN as the “Arn” property, and the unique, internal identifier for the IAM entity as the “UserId” property.

Check out the example below:

PS /Users/tsulli> Get-STSCallerIdentity

Account      Arn                                     UserId
-------      ---                                     ------
xxxxyyyyzzzz arn:aws:iam::xxxxyyyyzzzz:user/joeschmo AIDAR61T56KA9

Make sure you follow me on Twitter and check out my YouTube channel for more cloud and software information! Also, check out the AWS PowerShell examples in the navigation menu at the top of the site!