Last active
June 22, 2018 18:44
-
-
Save gene1wood/9eecb4306b94f202026e to your computer and use it in GitHub Desktop.
Method to determine the AWS account ID of your account using boto
This file contains hidden or 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
#!/usr/bin/env python | |
import boto, boto.jsonresponse | |
conn = boto.connect_sts() | |
e = boto.jsonresponse.Element() | |
boto.jsonresponse.XmlHandler(e, conn).parse(conn.make_request('GetCallerIdentity',{},'/','POST').read()) | |
e['GetCallerIdentityResponse']['GetCallerIdentityResult']['Account'] |
This file contains hidden or 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
#!/usr/bin/env python | |
import boto | |
metadata = boto.utils.get_instance_metadata(timeout=1, num_retries=1) | |
if 'iam' in metadata: | |
# We're running in an ec2 instance, get the account id from the | |
# instance profile ARN | |
return metadata['iam']['info']['InstanceProfileArn'].split(':')[4] | |
else: | |
try: | |
# We're not on an ec2 instance but have api keys, get the account | |
# id from the user ARN | |
return boto.connect_iam().get_user().arn.split(':')[4] | |
except: | |
# We don't have IAM or user credentials | |
return False |
@rbowlby , good call. I've updated it to accommodate ec2 IAM roles and lambda functions. I've also created a gist for how to do this with boto3 : https://gist.github.com/gene1wood/6d4974b7503336d642c9
I've added a new approach above which uses the new STS GetCallerIdentity method. This will work for users, roles, lambda, everything except an ec2 instance with no IAM role.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not workable when using ec2 IAM roles. :(