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, no_role: nil) ⇒ Main

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



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

def initialize(path: nil, profile: default, mfa_code: nil, no_role: 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
  @no_role = no_role
end

Instance Method Details

#assume_roleObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/aws_runas/main.rb', line 44

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') unless ENV.include?('AWS_SESSION_TOKEN')
  if @no_role
    raise 'No mfa_serial in selected profile, session will be useless' if mfa_serial.nil?
    @role_credentials = sts_client.get_session_token(
      duration_seconds: 3600,
      serial_number: mfa_serial,
      token_code: @mfa_code
    ).credentials
  else
    @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
end

#credentials_envObject



66
67
68
69
70
71
72
# File 'lib/aws_runas/main.rb', line 66

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



74
75
76
77
78
# File 'lib/aws_runas/main.rb', line 74

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

#sts_clientObject



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

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