Module: Fog::AWS::CredentialFetcher::ServiceMethods

Instance Method Summary collapse

Instance Method Details

#fetch_credentials(options) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/fog/aws/credential_fetcher.rb', line 10

def fetch_credentials(options)
  if options[:use_iam_profile] && Fog.mocking?
    Fog::Compute::AWS::Mock.data[:iam_role_based_creds]
  end
  if options[:use_iam_profile]
    begin
      connection = options[:connection] || Excon.new(INSTANCE_METADATA_HOST)
      role_name = connection.get(:path => INSTANCE_METADATA_PATH, :expects => 200).body
      role_data = connection.get(:path => INSTANCE_METADATA_PATH+role_name, :expects => 200).body
      az_data = connection.get(:path => INSTANCE_METADATA_AZ, :expects => 200).body
      region = az_data[0..-2] # get region from az

      session = Fog::JSON.decode(role_data)
      credentials = {}
      credentials[:aws_access_key_id] = session['AccessKeyId']
      credentials[:aws_secret_access_key] = session['SecretAccessKey']
      credentials[:aws_session_token] = session['Token']
      credentials[:aws_credentials_expire_at] = Time.xmlschema session['Expiration']

      # set region by default to the one the instance is in.
      credentials[:region] = region
      #these indicate the metadata service is unavailable or has no profile setup
      credentials
    rescue Excon::Error => e
      Fog::Logger.warning("Unable to fetch credentials: #{e.message}")
      super
    end
  else
    super
  end
end