简体   繁体   中英

Rails: How to reuse AWS credentials from ECS using containers

We have deployed Rails application on AWS(using docker image within container) and using S3 and SES services to upload files and sending Emails.Both We require AWS access_key_id, secret_access_key and session_token to communicate with AWS S3 and SES. We use Aws::ECSCredentials services to get AWS credentials which lasts 6 hours.

After 5.55 hours, we again fetch credentials using Aws::ECSCredentials.new() api call. We use CarrierWave to upload files to AWS S3 and using CarrierWave initializer as below to set credentials and this works only first 6 hours until credentials do not expires.

CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: "AWS",
    aws_access_key_id: Settings.amazon.access_key_id,
    aws_secret_access_key: Settings.amazon.secret_access_key,
    region: Settings.amazon.region,
  }

  config.storage = :fog
  config.fog_directory  = Settings.amazon.attachments_bucket
  config.fog_public     = false
end

Once first time set credentials expire, we again make a call to Aws::ECSCredentials.new() to get new credentials. To use new credentials, we have to reinitialize CarrierWave in ImageUploader(inherited from CarrierWave) as below.

class AvatarUploader < CarrierWave::Uploader::Base
  storage :fog


  **def initialize(*)
    super
    self.fog_credentials = {
      :provider               => 'AWS',              # required
      :aws_access_key_id      => 'YOURAWSKEYID',     # required
      :aws_secret_access_key  => 'YOURAWSSECRET',    # required
    }
    self.fog_directory = "YOURBUCKET"
  end
end

Is this approach fine to re-initialize CarrierWave everytime? I fear this may create Ruby memory issue by creating garbage objects. Can someone please help in this? Is there any better approach to handle it?

Is your company using AWS Single Sign-On (AWS SSO)? If not, I would recommend doing so. This way you could configure the AWS CLI to use those IAM roles securely to have sessions of a desired time period with refreshing tokens. You can find more details at the official docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM