Upload gzip files to S3 and serve by Cloudflare in Ruby


This article elaborates the following actions:

  • Create IAM which has only S3 access permission in AWS
  • Upload gzip files to AWS S3 using RubyGems
  • Distribute the files using Cloudflare which is CDN

This plan is safe and cheap!


😎 Create S3 Bucket

  • Access AWS Console
  • Go to Amazon Web Services > S3 > Create Bucket > Set bucket name like “image.example.com”

🐝 Create IAM

Let’s create IAM which has only S3 access permission in AWS.

  • Access AWS Console
  • Go to Amazon Web Services > Security & Identity > Identity and Access Management
  • Go to Users > Create New User > Get AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY of your IAM
  • Go to Policies > Create Policy > Copy an AWS Managed Policy > Select AmazonS3FullAccess > Change ARN to your bucket “arn:aws:s3:::image.example.com*”
  • Go to Users > Select your user name > permissions > Attach Policy > the upper policy

After the above setting process, you can use only S3 by the IAM.

đŸč Configuration on Cloudflare

Please read Cloudflare official document,
the following procedure is summary:

If your domain is “example.com” and you want to use the CNAME “files” you’ll need to make sure the S3 bucket name is “files.example.com”.
Amazon requires that the CNAME matches the bucket name files.

🎃 Upload gzip files to S3

Add the following gems and execute bundle install:

gem 'aws-sdk', '~> 2'

Add ENV['AWS_ACCESS_KEY_ID'] and ENV['AWS_SECRET_ACCESS_KEY'] to environment variable in your apps.
RubyGem figaro is one of the good solution in Rails application with Heroku or Dokku.

After setting the environment variable, you can upload any file to S3.
(Tips: I think compressing mp3 files is not good. Safari cannot play the file.)

require 'active_support/gzip'
require 'aws-sdk'

content = File.read('file/path/to')
gzip_data = ActiveSupport::Gzip.compress(content)

s3 = Aws::S3::Client.new(region: 'ap-northeast-1')
s3.put_object(
acl: 'public-read',
bucket: 'BUCKET_NAME',
content_type: 'image/jpeg',
content_encoding: 'gzip',
key: 'S3_KEY_LIKE_FILE_PATH',
body: gzip_data
)
s3.public_url #=> Return URL of the uploaded file

🏈 Special Thanks

đŸ–„ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!