Get AWS Account ID from Boto

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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 find the ID of this AWS Account?

回答1:

The AccountID can be grabbed from the get-caller-identity sts function. This returns an "Account" field:

client = boto3.client("sts", aws_access_key_id=access_key, aws_secret_access_key=secret_key) account_id = client.get_caller_identity()["Account"] 


回答2:

Something like this will work:

import boto3  ACCESS_KEY = 'FOO' SECRET_KEY = 'BAR'  iam = boto3.resource('iam',     aws_access_key_id=ACCESS_KEY,     aws_secret_access_key=SECRET_KEY, ) account_id = iam.CurrentUser().arn.split(':')[4]  print account_id 

If you use EC2 IAM roles, you can omit all of the access/secret key stuff and the code becomes simply:

iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] 


回答3:

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).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!