sammms
sammms

Reputation: 677

How can I programmatically read metadata from an AWS S3 Object in Rails?

My app is storing files on AWS S3. When the files are retrieved, some of them are missing a metadata field. I'd like to write a service that lets me check the files to see if the metadata field is present and valid after they have been retrieved from S3. I feel like it should be as simple as my_object.show_metadata, but I'm having trouble tracking down the solution. There is a AWS::S3::Object#metadata method, but when I try to use it I get the following error:

*** NoMethodError Exception: undefined method `set?' for # < Hash::0x007ffa547a9350>

Any insight or questions to help me find my blind spot on this one is appreciated.

UPDATE: The issue has been resolved. The correct way of doing what this question asks is in fact the AWS::S3::Object#metadata method. The issue in this case is the permissions must be explicitly set when the S3 object is created. Before the fix:

Aws::S3::Object.new(
  region: 'us-east-1',
  access_key_id: ENV['AWS_ACCESS_KEY_ID'],
  secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
  bucket_name: "foo",
  key: key
)

After the fix:

Aws.config.update({
  credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
})

Aws::S3::Object.new(
  region: 'us-east-1',
  bucket_name: "foo",
  key: key
)

After adjusting my code I was able to use all of the AWS S3 methods successfully, including #metadata.

Upvotes: 2

Views: 681

Answers (1)

sammms
sammms

Reputation: 677

The correct way of doing what this question asks is in fact the AWS::S3::Object#metadata method. The issue in this case is the permissions must be explicitly set when the S3 object is created. Before the fix:

Aws::S3::Object.new(   
    region: 'us-east-1',   
    access_key_id: ENV['AWS_ACCESS_KEY_ID'],   
    secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],   
    bucket_name: "foo",   
    key: key 
)

After the fix:

Aws.config.update({   
    credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], 
    ENV['AWS_SECRET_ACCESS_KEY']) 
}) 

Aws::S3::Object.new(   
    region: 'us-east-1',   
    bucket_name: "foo",  
    key: key 
)

After adjusting my code I was able to use all of the AWS S3 methods successfully, including #metadata.

Upvotes: 1

Related Questions