amazon-web-servicesfaradayaws-sdk-ruby

Aws SDK Ruby - retrieve credentials automatically when configuring Faraday


I enjoy using the AWS SDK without having to specify where to find the credentials, it makes it easier to configure on multiple environment where different types of credentials are available.

The AWS SDK for Ruby searches for credentials [...]

Is there some way I can retrieve the code that does this to configure Faraday with AWS ? In order to configure Faraday I need something like

faraday.request(:aws_sigv4,
      service: 'es',
      credentials: credentials,
      region: ENV['AWS_REGION'],
    )

Now I would love that this credentials be picked "automatically" as in the aws sdk v3. How Can I do that ?

(ie where is the code in the AWS SDK v3 that does something like

credentials = Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
unless credentials.set?
  credentials = Aws::InstanceProfileCredentials.new
end
...

Solution

  • The class Aws::CredentialProviderChain is the one in charge of resolving the credentials, but it is tagged as @api private so there's currently no guarantee it will still be there after updates (I've opened a discussion to make it public).

    If you're okay to use it, you can resolve credentials like this. I'm going to test it in CI (ENV creds), development (Aws config creds), and staging/production environments (Instance profile creds).

    Aws::CredentialProviderChain.new.resolve

    You can use it in middlewares like this (for example configuring Elasticsearch/Faraday)

    faraday.request(:aws_sigv4,
      service: 'es',
      credentials: Aws::CredentialProviderChain.new.resolve,
      region: ENV['AWS_REGION'],
    )
    end