Forked from gene1wood/01_get_account_id_for_user_ec2instance_role_or_lambda.py
Created
September 15, 2016 20:16
-
-
Save bkruger99/4761f53a0684fb3ad71a0c71497a609e 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment