Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save gene1wood/6d4974b7503336d642c9 to your computer and use it in GitHub Desktop.
Save gene1wood/6d4974b7503336d642c9 to your computer and use it in GitHub Desktop.
Method to determine your AWS account ID using boto3 for either a user or an ec2 instance or lambda function
import boto3
print(boto3.client('sts').get_caller_identity()['Account'])
aws sts get-caller-identity --query 'Account' --output text
# This method is no longer needed with the release of the STS GetCallerIdentity method
def get_account_id(context):
return context.invoked_function_arn.split(':')[4]
def lambda_handler(event, context):
print("My account ID is %s" % get_account_id(context))
# This method is no longer needed with the release of the STS GetCallerIdentity method
from botocore.vendored import requests
import boto3
def get_account_id():
try:
# We're running in an ec2 instance, get the account id from the
# instance profile ARN
return requests.get(
'http://169.254.169.254/latest/meta-data/iam/info/',
timeout=1).json()['InstanceProfileArn'].split(':')[4]
except:
pass
try:
# We're not on an ec2 instance but have api keys, get the account
# id from the user ARN
return boto3.client('iam').get_user()['User']['Arn'].split(':')[4]
except:
pass
return False
# This method is no longer needed with the release of the STS GetCallerIdentity method
import urllib2, json
import boto3
def get_account_id():
try:
# We're running in an ec2 instance, get the account id from the
# instance profile ARN
return json.loads(urllib2.urlopen(
'http://169.254.169.254/latest/meta-data/iam/info/',
None,
1).read())['InstanceProfileArn'].split(':')[4]
except:
pass
try:
# We're not on an ec2 instance but have api keys, get the account
# id from the user ARN
return boto3.client('iam').get_user()['User']['Arn'].split(':')[4]
except:
pass
return False
@MoOmEeN
Copy link

MoOmEeN commented Feb 26, 2016

Does not really work for me when used in Lambda function :/
first method fails with:

<urlopen error [Errno 111] Connection refused>

second with:

An error occurred (ValidationError) when calling the GetUser operation: Must specify userName when calling with non-User credentials

@gene1wood
Copy link
Author

@MoOmEeN good catch. I've added a new file that covers lambda since the urllib2 and requests ones only work for users and ec2 instances

@sandyhider
Copy link

sandyhider commented Sep 19, 2016

I was trying to figure out how to get the account number when I assumed a role to access resources in a second account. In this case the get_user() fails: "An error occurred (ValidationError) when calling the GetUser operation: Must specify userName when calling with non-User credentials"

I found that users list_users works cross accounts as long as there is at least one user account created:
account = assumed_session.client('iam').list_users(MaxItems=1)["Users"][0]["Arn"].split(':')[4]

@gene1wood
Copy link
Author

gene1wood commented Oct 6, 2016

With the release of the new STS GetCallerIdentity method, there's no more need for different processes for users, ec2 instances, roles and lambda. It can all now be done with the example above

@kuharan
Copy link

kuharan commented Apr 8, 2020

import boto3 print(boto3.client('sts').get_caller_identity()['Account'])

This doesn't seem to work now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment