Class: AwsRunAs::Main

Inherits:
Object
  • Object
show all
Defined in:
lib/aws_runas/main.rb

Overview

Main program logic for aws-runas - sets up sts asession and assumed role, and hands off environment to called process.

Instance Method Summary collapse

Constructor Details

#initialize(path: nil, profile: default, mfa_code: nil) ⇒ Main

Instantiate the object and set up the path, profile, and populate MFA



24
25
26
27
28
29
30
31
32
# File 'lib/aws_runas/main.rb', line 24

def initialize(path: nil, profile: default, mfa_code: nil)
  cfg_path = if path
               path
             else
               AwsRunAs::Config.find_config_file
             end
  @cfg = AwsRunAs::Config.new(path: cfg_path, profile: profile)
  @mfa_code = mfa_code
end

Instance Method Details

#assume_roleObject



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/aws_runas/main.rb', line 43

def assume_role
  session_id = "aws-runas-session_#{Time.now.to_i}"
  role_arn = @cfg.load_config_value(key: 'role_arn')
  mfa_serial = @cfg.load_config_value(key: 'mfa_serial')
  @role_credentials = Aws::AssumeRoleCredentials.new(
    client: sts_client,
    role_arn: role_arn,
    serial_number: mfa_serial,
    token_code: @mfa_code,
    role_session_name: session_id
  ).credentials
end

#credentials_envObject



56
57
58
59
60
61
62
# File 'lib/aws_runas/main.rb', line 56

def credentials_env
  env = {}
  env['AWS_ACCESS_KEY_ID'] = @role_credentials.access_key_id
  env['AWS_SECRET_ACCESS_KEY'] = @role_credentials.secret_access_key
  env['AWS_SESSION_TOKEN'] = @role_credentials.session_token
  env
end

#handoff(command: nil, argv: nil) ⇒ Object



64
65
66
67
68
# File 'lib/aws_runas/main.rb', line 64

def handoff(command: nil, argv: nil)
  env = credentials_env
  command = AwsRunAs::Utils.shell unless command
  exec(env, command, *argv)
end

#sts_clientObject



34
35
36
37
38
39
40
41
# File 'lib/aws_runas/main.rb', line 34

def sts_client
  region = @cfg.load_config_value(key: 'region')
  region = 'us-east-1' unless region
  Aws::STS::Client.new(
    profile: @cfg.load_source_profile,
    region: region
  )
end