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]}"