问题
Does anyone know how to get AWS account number using AWS Powershell? Doesn't look like there's an API available for that.
回答1:
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
回答2:
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.
回答3:
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
}
回答4:
Nice and simple
(Get-STSCallerIdentity).Account
来源:https://stackoverflow.com/questions/30656618/aws-powershell-to-retrieve-aws-account-number