Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aws::S3::Presigner undefined method credentials for nil:NilClass in Ruby

i have use aws-sdk-core gem i am getting error during getting url form aws following is my code

  def initialize(bucket:, region:)
    @bucket = bucket
    client = Aws::S3::Client.new(region: region)
    @signer = Aws::S3::Presigner.new(client: client)
  end

  def sign(key, expires_in: 3600)
    @signer.presigned_url(:get_object, bucket: @bucket, key: key,    expires_in: expires_in)
  end

i am getting error

NoMethodError - undefined method `credentials' for nil:NilClass:
  aws-sdk-core (2.1.15) lib/aws-sdk-core/signers/v4.rb:24:in `initialize'
  aws-sdk-core (2.1.15) lib/aws-sdk-core/s3/presigner.rb:88:in `block in sign_but_dont_send'

If anyone known how get presigned url please lets us known

Thanks

like image 451
SarKar Avatar asked Aug 25 '15 09:08

SarKar


1 Answers

The unhelpful error message indicates that you have not configured AWS credentials. These are need to generate the signature. If you had used the client to send a request you would have gotten a more helpful error message indicating that credentials were required.

def initialize(bucket:, region:)
  @bucket = bucket
  creds = Aws::Credentials.new('ACCESS_KEY', 'SECRET_ACCESS_KEY')
  client = Aws::S3::Client.new(region: region, credentials, creds)
  @signer = Aws::S3::Presigner.new(client: client)
end

def sign(key, expires_in: 3600)
  @signer.presigned_url(:get_object, bucket: @bucket, key: key, expires_in: expires_in)
end

Not related to your problem, but you can use the resource interface for S3 which cleans up the code a bit.

def initialize(bucket:, region:)
  @bucket = Aws::S3::Bucket.new(bucket, {
    region: region,
    credentials: Aws::Credentials.new('ACCESS_KEY', 'SECRET_ACCESS_KEY'),
  })
end

def sign(key, expires_in: 3600)
  @bucket.object(key).presigned_url(:get, expires_in: expires_in)
end

While I showed how to configure credentials in code, I strongly recommend against this. You should export credentials to ENV before launching your applications or put them in the shared credentials file.

$ export AWS_ACCESS_KEY_ID=...
$ export AWS_SECRET_ACCESS_KEY=...

Or put the following in ~/.aws/credentials

[default]
aws_access_key_id=...
aws_secret_access_key=...

If you use the ENV or shared credentials file, then you no longer need to configure them in code. The SDK will attempt to source these locations when they are not given to the client constructor.

like image 148
Trevor Rowe Avatar answered Nov 02 '22 09:11

Trevor Rowe