Downloading a Bucket from Amazon S3 using Ruby

This little script was written using Ruby 2.5.1 and uses the aws-sdk-s3 gem.

Folder structure:

    download_s3/
    - download_s3.rb
    - s3.yml
    - Gemfile

download_s3.rb:

    #!/usr/bin/env ruby
    require 'yaml'
    require 'aws-sdk-s3'

    s3_file = File.join(__dir__, 's3.yml')
    config = YAML.load(File.read(s3_file))

    backup_folder = config['backup_folder']
    region = config['region']
    bucket = config['bucket']
    access_key_id = config['access_key_id']
    secret_access_key = config['secret_access_key']

    Aws.config.update({
      credentials: Aws::Credentials.new(access_key_id, secret_access_key),
      region: region
    })

    s3 = Aws::S3::Resource.new
    s3_bucket = s3.bucket(bucket)
    s3_bucket.objects.each do |item|
      puts "Name:  #{item.key}"
      backup_file = File.join(backup_folder, bucket, item.key)
      parent = File.dirname(backup_file)
      if not File.directory?(parent)
        FileUtils.mkpath(parent)
      end
      item.get(response_target: backup_file)
    end

s3.yml:

    backup_folder: <your_backup_folder>
    region: <your_region>
    bucket: <your_bucket>
    access_key_id: <your_access_key_id>
    secret_access_key: <your_secret_access_key>

Gemfile:

    source 'https://rubygems.org'
    gem 'aws-sdk-s3', '1.17.0'