Skip to content

Instantly share code, notes, and snippets.

@mhjwork
Last active August 29, 2015 14:16
Show Gist options
  • Save mhjwork/cb2d4223ae8d883d519e to your computer and use it in GitHub Desktop.
Save mhjwork/cb2d4223ae8d883d519e to your computer and use it in GitHub Desktop.
Assuming an AWS STS role (with multi-factor authentication) using Ruby
def assumeRole(region: 'eu-west-1', role_arn: nil, session: 'temp', duration: 3600, mfa_arn: nil, token: nil)
# returns a Credentials object for the assumed role, built from:
# region: the AWS region to connect to (default: eu-west-1),
# role_arn: the role ARN that you want to assume,
# session: the name you want to give the session (default: 'temp'),
# duration: seconds the assumed role is valid for (default: 3600),
# mfa_arn: the ARN for the MFA token associated with the user
# token: the 6-digit token ID from the MFA device
#
# This assumes that you have already defined your normal AWS credentials,
# either as environment variables, or in the .aws directory.
#
begin
# Create an AWS STS Client object in the specified region
user_client = Aws::STS::Client.new(region: region)
# Create the assumed role credentials
assumed_role = Aws::AssumeRoleCredentials.new(
client: user_client,
role_arn: role_arn,
role_session_name: session,
duration_seconds: duration,
serial_number: mfa_arn,
token_code: token
)
# return the assumed role credentials object
return assumed_role
# Error handling
rescue StandardError => e
puts "Error in assumeRole: #{e.message}"
return nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment