12

Does anyone know how to get AWS account number using AWS Powershell? Doesn't look like there's an API available for that.

Anthony Neace
  • 21,951
  • 6
  • 100
  • 116
minisch
  • 241
  • 3
  • 14

4 Answers4

11

Not directly. However, your Account ID is a part of the Arn of resources that you create... and those that are automatically created for you. Some resources will also list you as an OwnerId.

The Default Security Group is automatically created for you in each region, and cannot be deleted. This makes it a reliable candidate for retrieving our account Id.

Example:

PS C:/> $accountId = @(get-ec2securitygroup -GroupNames "default")[0].OwnerId

PS C:/> $accountId
000011112222
Anthony Neace
  • 21,951
  • 6
  • 100
  • 116
  • 2
    Great answer above, thanks. I noticed that you can get the account alias which in my case was what I needed. To do so use Get-IamAccountAlias – CarlR Jun 30 '15 at 12:31
2

Nice and simple

(Get-STSCallerIdentity).Account
demonicdaron
  • 1,236
  • 14
  • 27
1

I was unable to comment on the other provided answer, so I'll have to offer my own solution as a slight modification.

I do believe the OwnerId on all groups will be the Account Id. However you may not have a "default" group. I recommend leaving out the -GroupNames "default". Also, I'm showing my example using a SAML token, as that is our case coming in with AD authorization.

$awsAccountNumber = (get-ec2securitygroup -ProfileName saml -Region us-west-2)[0].OwnerId

Hopefully that will be of some use.

0

I use Get-STSCallerIdentity.

Here is a code snippet that I use:

    foreach ($ProfileName in $Profiles){
    if ($ProfileName -match 'gov') { 
        Initialize-AWSDefaultConfiguration -ProfileName $ProfileName -Region us-gov-east-1
        $STSCallerIdentity = Get-STSCallerIdentity
    }
    else { 
        Initialize-AWSDefaultConfiguration -ProfileName $ProfileName -Region us-east-1 
        $STSCallerIdentity = Get-STSCallerIdentity
    }