-
-
Save bodsch/e02534f6417b44d80a05c41dd225023a to your computer and use it in GitHub Desktop.
Ruby AWS SDK v2 IAM user MFA example
This file contains 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
# shows how to use the Ruby AWS SDK to list EC2 instance IDs | |
# when your API credentials have been placed under MFA requirements | |
# Prerequisites: | |
# you are running on a host that already has the AWS CLI set up with an IAM key pair | |
# that can describe EC2 instances (OTHERWISE, just pass a | |
# secret_access_id / secret_access_key pair to the STS client initializer) | |
# You have installed the Ruby AWS SDK Gem | |
# http://aws.amazon.com/sdk-for-ruby/ | |
# gem install aws-sdk | |
# to run, save this gist as mfa_example.rb and then: | |
# ruby mfa_example.rb <MFA_serial_num> <MFA_token> | |
# you can get your serial by navigating to your user account's page | |
# in the AWS IAM console and scrolling all the way to the bottom. | |
# it's labeled "Multi-Factor Authentication Device" and has a format like this: | |
# arn:aws:iam::1234567890:mfa/johndoe | |
# the MFA token is the 6-digit code you get from your MFA device (like Google Authenticator or Duo Mobile) | |
require 'aws-sdk' | |
ENV['AWS_REGION'] = 'us-east-1' | |
ENV['AWS_MFA_SERIAL'] = ARGV[0] | |
ENV['AWS_MFA_TOKEN'] = ARGV[1] | |
sts = Aws::STS::Client.new | |
# here's what I'd do on an instance that has an attached IAM role capable of assuming the 'full-access-ec2-tags' role | |
# session = sts.assume_role( role_arn: ENV['ROLE_ARN'], role_session_name: 'foo' ) | |
# here's what I'd do on localhost. I'll continue as me, but with temporary credentials derived from my MFA authentication. | |
session = sts.get_session_token( duration_seconds: 900, serial_number: ENV['AWS_MFA_SERIAL'], token_code: ENV['AWS_MFA_TOKEN'] ) | |
# getting Aws::EC2::Errors::AuthFailure: AWS was not able to validate the provided access credentials | |
# failing to include session_token, which is nil by default, makes this whole thing fail!! | |
creds = Aws::Credentials.new( session.credentials.access_key_id, session.credentials.secret_access_key, session.credentials.session_token ) | |
ec2 = Aws::EC2::Client.new( credentials: creds ) | |
i = ec2.describe_instances | |
i[:reservations].each do |reservation| | |
reservation[:instances].each do |instance| | |
puts instance[:instance_id] | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment