如何通过非默认的 aws 配置文件与 aws sdk 进行连接交互?

How do I connect interact with the aws sdk via a aws profile that is not default?

我的组织使用联合访问 [在此处输入 link 描述][1] 到 aws,这意味着我需要经常重新生成我的 aws 凭据,所以经常对它们进行硬编码,甚至将它们设置为环境变量不是一个选项。

我找到了 http://docs.aws.amazon.com/sdkforruby/api/Aws/SharedCredentials.html#profile_name-instance_method 记录 class,但我无法真正将其转换为实际代码(请原谅我的无知,我不是计算机科学家,而是从事操作的)。

各种方法都试过了,还是一头雾水

rds = Aws::RDS::Resource.new(
  profile_name: 'foo'
)

无效。

查看 Aws::RDS::Resource 初始化方法,这应该可行。但是,您可能在 ENV['AWS_PROFILE'] 或 shared_config.profile_name 中有 profile_name,它覆盖了 @profile_name = options[:profile_name]。您可以调试它的一种方法是使用 pry gem,这将允许您查看这些变量在初始化方法中设置的内容。

# bundle open 'aws-sdk-core' 
# Find File 'aws-sdk-core/lib/aws-sdk-core/shared_credentials.rb', line 24
# add require pry; binding.pry under the last @profile_name variable in aws-sdk-core/lib/aws-sdk-core/shared_credentials.rb'

def initialize(options = {})
  shared_config = Aws.shared_config
  @path = options[:path]
  @path ||= shared_config.credentials_path
  @profile_name = options[:profile_name]
  @profile_name ||= ENV['AWS_PROFILE']
  @profile_name ||= shared_config.profile_name
  require pry; binding.pry 
  if @path && @path == shared_config.credentials_path
    @credentials = shared_config.credentials(profile: @profile_name)
  else
    config = SharedConfig.new(
      credentials_path: @path,
      profile_name: @profile_name
    )
    @credentials = config.credentials(profile: @profile_name)
  end
end

一旦您 运行 您创建的 rds 变量,它将触发 pry 控制台在该方法内打开。您现在可以访问 shared_config.profile_name、ENV['AWS_PROFILE' 以及选项。

pry(main)> options
         => {:profile_name=>"foo"}
           @profile_name 
         => 'foo' or whatever its set to.
           ENV['AWS_PROFILE']
         => see if it returns some value 
           shared_config.profile_name
         => see if it returns some value