Browsed by
Tag: AWS

AWS get the current users ARN – BASH

AWS get the current users ARN – BASH

I have already posted on how to get the AWS username from the users arn for both Ruby and Python. But what about BASH?

I love to use Bash to quickly whip something together and the awscli makes it super easy. However the get-caller-identity method was not introduced until version 1.10 of the cli. So you may need to upgrade your cli first. On a Mac/Linux desktop/server this is easy.

pip install --upgrade awscli

This should upgrade you to the latest version. At the time of this article it is/was 1.11.2.

Now the sts get-caller-identity should be working

aws sts get-caller-identity

It will return something like this:

{
"Account": "123456789012",
"UserId": "Abcdefg123456789XYZ01",
"Arn": "arn:aws:iam::123456789012:user/bob"
}

Now we can parse that, we can either use jq, or –query. I will show both.

First for jq, which is a favorite tool around my shop:

aws sts get-caller-identity --output json | jq -r '.Arn' | cut -f 2 -d '/'

It looks a little messy but works as long as you have jq installed, but what about –query:

aws sts get-caller-identity --output text --query 'Arn' | cut -f 2 -d '/'

I use –output text to eliminate the double quotes .

As you can see bash, IMHO, is a much easier tool to work with using the aws cli to quickly build small shell scripts.

 

AWS get the current users ARN – Ruby

AWS get the current users ARN – Ruby

I already wrote a post on how to do this using Python. But here is how to do the same thing in Ruby:

I write a lot of automation scripts. I switch back and forth using both Ruby and Python. So when using the aws sdk in a ruby script I want to know who is running the script. I like to use the aws profile(s) for key rather than having the keys stored in yet another place on the users machine. I normally either ask the user to enter the profile name or have it passed on the command line. The sdk offers a couple of ways to get at the AWS user associated with they kepair in the profile.

First there is the IAM get-user class, however this class requires that the profile have IAM access which most profiles should not have. So this is not a good way to get at this information.

The second way is using STS or Security Token Service . This API offers a method called GetCallerIdentity.  This method returns the Account, ARN and UserId for the aws credentials used to make the request. So let’s see how to do this in Ruby.

First we use the SharedCredentials API to create a new SharedCredentials object for the profile information:

myCredentials = Aws::SharedCredentials.new(profile_name: myProfile)

Next we create a new STS Client object using those credentials:

myStsClient = Aws::STS::Client.new(credentials: myCredentials)

And finally call the get_caller_identity method:

mySts = myStsClient.get_caller_identity()

That object then returns the following elements:

puts "My Account #{myStsClient.account}"
puts "My ARN #{myStsClient.arn"
puts "My User id #{myStsClient.user_id}"

Now if you use this you will see that the UserID is not what you were expecting. It returns the unique identifier for the profile. That is well and good, but I want to get the username. Fortunately it is part of the ARN. so we can split it out like so:

puts "My User #{myStsClient.arn.split('/')[-1]}"

Now we have something we can use.

Here it is all put together:

#!/usr/bin/env ruby
require 'aws-sdk'
require 'optparse'

options = {:myProfile => nil }

parser = OptionParser.new do|opts|
  opts.banner = "Sample STS Script [options]"
  opts.on('-m', '--my-profile myProfile', 'myProfile') do |myProfile|
    options[:myProfile] = myProfile;
  end

  opts.on('-h', '--help', 'Displays Help') do
    puts opts
    exit
  end
end

parser.parse!

myProfile = options[:myProfile]

myCredentials = Aws::SharedCredentials.new(profile_name: myProfile)
myStsClient = Aws::STS::Client.new(credentials: myCredentials)
mySts = myStsClient.get_caller_identity()

puts "My Account #{mySts.account}"
puts "My ARN #{mySts.arn}"
puts "My User id #{mySts.user_id}"
puts "My User #{mySts.arn.split('/')[-1]}"
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))