使用块有条件地设置选项

时间:2015-11-27 03:53:14

标签: ruby fog

我正在构建一个模块,该模块提供了一些使用Fog gem与AWS CloudWatch服务交互的功能。如果未指定凭据,它将自动使用ENV中设置的任何内容或使用运行代码的实例的IAM角色。其他时候,我想明确传递凭据以访问其他AWS账户。这是一个示例课程,演示了我希望如何工作:

class MyAlarmGetter
  include CloudWatchClient

  default_account_alarms = get_all_alarms

  other_account_alarms = with_aws_credentials(account2) do
    get_all_alarms
  end

  def account2
    {
      aws_access_key_id: 'abc123',
      aws_secret_access_key: 'abc123'
    }
  end
end

这是该模块到目前为止的样子:

module CloudWatchClient
  def with_aws_credentials(creds)
    # Set credentials here!
    yield
  end

  def get_all_alarms
    cloud_watch_client.alarms.all
  end

  def cloud_watch_client(creds = ENV['FOG_CREDENTIAL'] ? {} : { use_iam_profile: true })
    Fog::AWS::CloudWatch.new(creds)
  end
end

我一直在想办法只能覆盖with_aws_credentials块上下文中的默认凭据。

1 个答案:

答案 0 :(得分:1)

要支持这种接口,您可以将creds参数保存到实例变量中,例如@creds

module CloudWatchClient
  def with_aws_credentials(creds)
    # set given context
    @creds = creds

    result = yield

    # reset context
    @creds = nil

    result 
  end

  def get_all_alarms
    cloud_watch_client.alarms.all
  end

  def cloud_watch_client(creds = ENV['FOG_CREDENTIAL'] ? {} : { use_iam_profile: true })
    # check if context is given and use it
    creds = @creds || creds

    Fog::AWS::CloudWatch.new(creds)
  end
end

上面的代码只是一个示例,只需最少的代码调整。