1

I want to write a python program to check which account I am in by using account alias (I have multiple Tennants et up on AWS). I think aws iam list-account-aliases return what exactly I am looking for but it is a command line results and I am not sure what is the best to capture as variable in a python program.

Also I was reading about the aws iam list-account-aliases and they have a output section mentioned AccountAliases -> (list). (https://docs.aws.amazon.com/cli/latest/reference/iam/list-account-aliases.html)

I wonder what this AccountAliases is? an option? a command? a variable? I was a little bit confused here.

Thank you!

ASU_TY
  • 617
  • 2
  • 7
  • 12

2 Answers2

2

Use Boto3 to get the account alias in python. Your link points to aws-cli.

Here is the link for equivalent Boto3 command for python: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.list_account_aliases

Sample code:

import boto3

client = boto3.client('iam')

response = client.list_account_aliases()

Response:

{
    'AccountAliases': [
        'myawesomeaccount',
    ],
    'IsTruncated': True,
}
Asdfg
  • 11,362
  • 24
  • 98
  • 175
1

Account alias on AWS is a readable alias created against AWS user's account id. You can find more info here : https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html

AWS has provided a very well documented library for Python called Boto3 which can be used to obtain connect to your AWS account as client, resource or session (more information on these in SO answer here: Difference in boto3 between resource, client, and session?)

For your use case you can connect to your AWS as client with iam label:

import boto3

client = boto3.client(
            'iam', 
            region_name="region_name",
            aws_access_key_id="your_aws_access_key_id",
            aws_secret_access_key="your_aws_secret_access_key")

account_aliases = client. list_account_aliases()

The response is a JSON object which can be traversed to get the desired information on aliases.

Shubham Mishra
  • 341
  • 1
  • 9