Skip to content

Instantly share code, notes, and snippets.

@gene1wood
Last active June 22, 2018 18:44
Show Gist options
  • Save gene1wood/9eecb4306b94f202026e to your computer and use it in GitHub Desktop.
Save gene1wood/9eecb4306b94f202026e to your computer and use it in GitHub Desktop.
Method to determine the AWS account ID of your account using boto
#!/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']
#!/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
Copy link

rbowlby commented Oct 27, 2015

Not workable when using ec2 IAM roles. :(

@gene1wood
Copy link
Author

@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

@gene1wood
Copy link
Author

gene1wood commented Oct 6, 2016

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