15

I have an AWS key and secret key and would like to call boto to get the account name.

I can get account ID, but the AWS account name is a mystery.

RichVel
  • 7,030
  • 6
  • 32
  • 48
blacksheep9000
  • 383
  • 2
  • 3
  • 6
  • Please check answers here http://stackoverflow.com/questions/36709461/get-aws-account-id-from-boto – Montaro Dec 14 '16 at 16:04
  • It appears that this question specifically refers to boto2 as boto3 wasn't out when this question was asked. Just for fun I checked and the initial commit was actually 6 hours after this question was posted: https://github.com/boto/boto3/commit/a33e1f8595e8d4cf70b8d5c0b1a7657124adc6a2 :) – Jake Oct 05 '17 at 15:06

4 Answers4

26

To get the AWS account alias in boto3:

alias = boto3.client('iam').list_account_aliases()['AccountAliases'][0]
  • While the API response allows for multiple account aliases, AWS docs on aliases say there can be only one per account.
  • The account alias is not the same as the account name, but it's alphanumeric and more usable than account number. The alias must be created under IAM settings for account (or using AWS CLI) - not all accounts will have an alias.
  • Getting the alias doesn't require as much privilege to access as getting the account name via the boto3 organizations service.

To get account ID (account number):

id = boto3.client('sts').get_caller_identity().get('Account')
RichVel
  • 7,030
  • 6
  • 32
  • 48
7

from Get AWS Account ID from Boto

id = boto3.client('sts').get_caller_identity().get('Account')

then

name =   boto3.client('organizations').describe_account(AccountId=id).get('Account').get('Name')
Community
  • 1
  • 1
G. Lasne
  • 71
  • 1
  • 3
3

Its late but might be helpful for future. If you are using organization service then using below code you can fetch Account Name.

org = boto3.client('organizations')
account_name = org.describe_account(AccountId='account-id').get('Account')
print(account_name ['Name'])

For more info

saranjeet singh
  • 868
  • 6
  • 17
2

It is only possible if you're using IAM and you want to retrieve that alias. If you have root credentials, it's not possible to retrieve the account name.

The related call is: get_account_alias()

http://boto.readthedocs.org/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.get_account_alias

xis
  • 24,330
  • 9
  • 43
  • 59
Adam Papai
  • 256
  • 2
  • 9