LoginSignup
0
0

More than 3 years have passed since last update.

S3に置いたActiveStorageをローカルに移す

Posted at

あまり使うことは無さそうですが、RailsのActiveStorageで管理しているファイルを、S3からローカル(disk)に移しました。

やり方を忘れないようにメモ。

ディレクトリ構造

S3では、ファイルはSU61LeyW6YcZtZaoNHSL2CTuのような名前でbucketに格納されています。

ローカルのディレクトリに置く場合は、storage/SU/61/SU61LeyW6YcZtZaoNHSL2CTuのようになっています。つまり、2階層のディレクトリが作られていて、1階層目はファイル名の先頭の2文字、2階層目は3文字目と4文字目がディレクトリ名になっています。

手順

S3からファイルをコピーする

tmpの下のstorageというディレクトリにコピーします。

$ mkdir tmp/storage
$ aws s3 cp s3://<bucket-name> ./tmp/storage --recursive

ActiveStorageのディレクトリに移す

次のRubyスクリプトで2階層のディレクトリを作りながらコピーします。
アプリケーションのルートディレクトリで実行します。

require 'fileutils'

src = "tmp/storage"
dst = "storage"

Dir.glob("#{src}/**/*").each do |source|
  next unless File.file?(source)
  file = File.basename(source)
  dir1, dir2, = file.scan(/\A(?<dir1>..)(?<dir2>..)/).flatten
  target = "#{dst}/#{dir1}/#{dir2}/#{file}"
  FileUtils.mkdir_p(File.dirname(target)) unless File.exist?(File.dirname(target))
  FileUtils.cp(source, target)
  puts target
end

後始末

コピーしてきたファイルや、作業用のディレクトリを削除します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0