Browsed by
Tag: Python

AWS get the current users ARN – Python

AWS get the current users ARN – Python

In writing scripts it is good to know who is running them. I create a lot of AWS python scripts. These examples are using python3 and boto3. I prefer to use the aws config profile for creating the sessions. It is easier on users and allows for multiple key pairs to be used and switched out easily.

devAWSSession = boto3.Session(profile_name=args.devProfile)

That works great for setting up a session, but what if you want to log the user behind that profile? Sometimes the profile names are not helpful. (I am looking at you “default”) The aws iam command has a get_user function that works great, if you have iam access. What if you don’t want all of your profiles to have IAM access, and you shouldn’t.

AWS provides another set of classes called “sts” or “Security Token Service”. With this service you can call get_caller_identity. This will give you back the account number, arn, and userid. However that is not the userid is not the user name you would expect, it actually returns the unique AWS user id. But the username is part of the arn. First let’s get the data, using the session from above:

mySts = myAWSSession.client('sts').get_caller_identity()
myArn = mysts["Arn"]

Now we have the complete arn “arn:aws:iam::123456789012:user/Bob”. So now we can do a normal splitĀ and get Bob from the arn:

myUser = myArn.split('/')[-1]

Now myUser = Bob

Super simple and easy

import boto3
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("-m", "--my-profile", dest = "myProfile", default = "default", help="My AWS Profile")

args = parser.parse_args()

myAWSSession = boto3.Session(profile_name=args.myProfile)

mySts = myAWSSession.client('sts').get_caller_identity()
myArn = mySts["Arn"]
myAccount = mySts["Account"]
myUser = myArn.split('/')[-1]

print("My profile user: {}".format(myUser))