Module: Jackal::Cfn::Utils::Fog

Includes:
Jackal::Cfn::Utils
Defined in:
lib/jackal-cfn/utils/fog.rb

Overview

Helper module for loading Fog APIs

Instance Method Summary collapse

Methods included from Jackal::Cfn::Utils

#snakecase, #transform_parameters

Instance Method Details

#api_assume_for(api, role) ⇒ Fog::Service

Note:

this is AWS specific

Assume the role for the API connection

Parameters:

  • api (Fog::Service)
  • role (String)

    name of role to assume

Returns:

  • (Fog::Service)

    assumed service



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/jackal-cfn/utils/fog.rb', line 47

def api_assume_for(api, role)
  Thread.current[:cfn_assume_apis] ||= Smash.new
  key = api.to_yaml_properties.group_by do |item|
    item.to_s.split('_').first
  end.values.sort_by(&:size).last.map do |var|
    [var, api.instance_variable_get(var)]
  end.flatten.compact.map(&:to_s).push(api.service_name).sort.hash
  if(Thread.current[:cfn_assume_apis].get(key, :expires).to_i < Time.now.to_i + 5)
    sts = ::Fog::AWS::STS.new(
      config.fetch(
        :api, :sts, config.get(
          :api, :default
        )
      )
    )
    result = sts.assume_role("jackal-cfn-#{Carnivore.uuid}", role).body
    Thread.current[:cfn_assume_apis][key] = Smash.new(
      :expires => Time.parse(result['Expiration']).to_i,
      :api => api.class.new(
        :aws_access_key_id => result['AccessKeyId'],
        :aws_secret_access_key => result['SecretAccessKey'],
        :aws_session_token => result['SessionToken']
      )
    )
  end
  Thread.current[:cfn_assume_apis].get(key, :api)
end

#api_for(type) ⇒ Fog::Service

Note:

extracts credentials from confg at :api -> [type | :default]

Provide API for given type

Parameters:

  • type (Symbol)

    Fog API (compute, orchestration, etc)

Returns:

  • (Fog::Service)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/jackal-cfn/utils/fog.rb', line 16

def api_for(type)
  klass = ::Fog.constants.detect do |const|
    snakecase(const).to_s == type.to_s
  end
  if(klass)
    credentials = config.fetch(
      :api, type, config.get(
        :api, :default
      )
    )
    if(credentials)
      key = credentials.to_a.flatten.push(klass).sort.hash
      Thread.current[:cfn_apis] ||= Smash.new
      unless(Thread.current[:cfn_apis][key])
        Thread.current[:cfn_apis][key] = ::Fog.const_get(klass).new(credentials)
      end
      Thread.current[:cfn_apis][key]
    else
      ArgumentError.new 'No credentials provided in configuration!'
    end
  else
    raise TypeError.new "Unknown API type requested (#{type})"
  end
end