Get AWS Account ID from Boto

后端 未结 3 1786
悲哀的现实
悲哀的现实 2020-12-16 10:05

I have an AWS_ACCESS_KEY_ID and an AWS_SECRET_KEY. These are active credentials, so they belong to an active user, who belongs to an AWS Account. How, using Boto3, do I fi

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 10:30

    The following function will get you the Account ID for your key pair:

    import boto3
    
    def get_aws_account_id(access_key, secret_key):
        sts = boto3.client(
            "sts", aws_access_key_id=access_key, aws_secret_access_key=secret_key,
        )
        user_arn = sts.get_caller_identity()["Arn"]
        return user_arn.split(":")[4]
    

    This works because user ARN is of the format "arn:aws:iam::ACCOUNT_ID:user/USERNAME". Splitting by colons, Account ID is the 4th item (0-indexed).

提交回复
热议问题