rcloneを使用してGoogleドライブからAmazon S3へバックアップを取ってみた

GoogleドライブからAmazon S3へのバックアップ方法を記載しました
2022.10.14

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは。ネクストモードの倉地です。
弊社内ではファイル共有ツールとしてGoogleドライブを使用していますが、万が一データが消失場合に備えてAmazon S3へバックアップを取得したいという要望があり、技術検証しましたのでこちらに共有できればと思います。

要件/環境

  • ローカル端末にrcloneを設定し、Googleドライブ(共有ドライブ)の特定のフォルダをAmazon S3へバックアップする ※今回は検証のため手動でコマンドを叩く
  • ローカル端末:Windows10,WSL(Ubuntu 20.04 on Windows)

そもそもrcloneとは?

rcloneとは、様々なクラウドサービス間でファイルとディレクトリを同期できるようにする、go言語を使用して開発されたオープンソースツールです。
詳しくはRCLONE公式ドキュメントをご確認ください。

はじめはiPaaSを使用してのバックアップを検討していましたが、料金が発生することやGoogleドライブ側のフォルダ構造をS3に反映することが難しいことが分かったため、rcloneを使用することになりました。

S3バケット設定

S3バケット作成

東京リージョンにnm-test-rcloneというS3バケットを作成します。※S3バケットの設定内容は基本的にデフォルトとしますが、バックアップ用途のためバージョニングのみ有効化します。

バケットポリシー設定

S3バケットを作成後、バケットポリシーにこちらを設定します。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::アカウントID:user/nm-rclone-user"
            },
            "Action": "*",
            "Resource": [
                "arn:aws:s3:::nm-test-rclone/*",
                "arn:aws:s3:::nm-test-rclone"
            ]
        }
    ]
}

IAM設定

IAMポリシー作成

IAMポリシー(nm-test-rclone)に下記のポリシーを設定します。※検証のため大きめに付与していますが、本番環境で使用の際は権限を適切に絞ってご使用ください。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:CreateAccessPoint",
                "s3:PutAnalyticsConfiguration",
                "s3:PutAccelerateConfiguration",
                "s3:DeleteObjectVersion",
                "s3:RestoreObject",
                "s3:DeleteAccessPoint",
                "s3:CreateBucket",
                "s3:ReplicateObject",
                "s3:PutEncryptionConfiguration",
                "s3:DeleteBucketWebsite",
                "s3:AbortMultipartUpload",
                "s3:PutLifecycleConfiguration",
                "s3:UpdateJobPriority",
                "s3:DeleteObject",
                "s3:DeleteBucket",
                "s3:PutBucketVersioning",
                "s3:PutMetricsConfiguration",
                "s3:PutReplicationConfiguration",
                "s3:PutObjectLegalHold",
                "s3:UpdateJobStatus",
                "s3:PutBucketCORS",
                "s3:PutInventoryConfiguration",
                "s3:PutObject",
                "s3:PutBucketNotification",
                "s3:PutBucketWebsite",
                "s3:PutBucketRequestPayment",
                "s3:PutObjectRetention",
                "s3:PutBucketLogging",
                "s3:PutBucketObjectLockConfiguration",
                "s3:ReplicateDelete"
            ],
            "Resource": "arn:aws:s3:::nm-test-rclone/*"
        }
    ]
}

IAMユーザー作成

今回はnm-rclone-userというIAMユーザーを作成します。AWSアクセスの種類は「アクセスキー -プログラムによるアクセス」のみを選択します。

「既存のポリシーを直接アタッチ」を選択し、先ほど作成したIAMポリシー(nm-test-rclone)を選択します。

IAMユーザー作成後はセキュリティ認証情報をダウンロードします。

rclone設定

rcloneのインストール

こちらのコマンドでrcloneをローカル端末(WSL)にインストールします。

$ curl https://rclone.org/install.sh | sudo bash

設定ファイルの作成①(Amazon S3)

まずはAmazon S3にアクセスするための設定を行います。下記のコマンドで対話形式で設定ファイルを作成します。

$ rclone config

対話型で設定を進めていきます

#新しいリモート設定を追加するため、「n」を入力します
Current remotes:

Name                 Type
====                 ====

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> n

#リモート設定名に「s3」と入力します
Enter name for new remote.
name> s3

#ストレージ種別ではS3を選択するため、「5」と入力します
Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.

~~省略~~
 5 / Amazon S3 Compliant Storage Providers including AWS, Alibaba, Ceph, China Mobile, Cloudflare, ArvanCloud, Digital Ocean, Dreamhost, Huawei OBS, IBM COS, IDrive e2, Lyve Cloud, Minio, Netease, RackCorp, Scaleway, SeaweedFS, StackPath, Storj, Tencent COS and Wasabi
   \ (s3)
 ~~省略~~
Storage> 5

#プロバイダはAWSを選択するため、「1」と入力します
Option provider.
Choose your S3 provider.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
 1 / Amazon Web Services (AWS) S3
   \ (AWS)
~~省略~~
provider> 1

#次の項目で認証情報を入力するため、「1」と入力します
Option env_auth.
Get AWS credentials from runtime (environment variables or EC2/ECS meta data if no env vars).
Only applies if access_key_id and secret_access_key is blank.
Choose a number from below, or type in your own boolean value (true or false).
Press Enter for the default (false).
 1 / Enter AWS credentials in the next step.
   \ (false)
 2 / Get AWS credentials from the environment (env vars or IAM).
   \ (true)
env_auth> 1

#IAMユーザーのアクセスキーを入力します
Option access_key_id.
AWS Access Key ID.
Leave blank for anonymous access or runtime credentials.
Enter a value. Press Enter to leave empty.
access_key_id> XXXXXXXXXXXXXXXX

#IAMユーザーのシークレットアクセスキーを入力します
Option secret_access_key.
AWS Secret Access Key (password).
Leave blank for anonymous access or runtime credentials.
Enter a value. Press Enter to leave empty.
secret_access_key> XXXXXXXXXXXXXXX

#東京リージョンを選択するため、「14」と入力します
Option region.
Region to connect to.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
~~省略~~
   / Asia Pacific (Tokyo) Region.
14 | Needs location constraint ap-northeast-1.
   \ (ap-northeast-1)
~~省略~~
region> 14

#デフォルトのS3 APIエンドポイントを使用するため、入力せずにエンターキーを押下します
Option endpoint.
Endpoint for S3 API.
Leave blank if using AWS to use the default endpoint for the region.
Enter a value. Press Enter to leave empty.
endpoint> 

#東京リージョンを選択するため、「14」と入力します
Option location_constraint.
Location constraint - must be set to match the Region.
Used when creating buckets only.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
~~省略~~
14 / Asia Pacific (Tokyo) Region
   \ (ap-northeast-1)
~~省略~~
location_constraint> 14

#ACLはprivateを選択するため、「1」と入力します
Option acl.
Canned ACL used when creating buckets and storing or copying objects.
This ACL is used for creating objects and if bucket_acl isn't set, for creating buckets too.
For more info visit https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl
Note that this ACL is applied when server-side copying objects as S3
doesn't copy the ACL from the source but rather writes a fresh one.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
   / Owner gets FULL_CONTROL.
 1 | No one else has access rights (default).
   \ (private)
~~省略~~
acl> 1

#サーバーサイド暗号化は使用しないため、「1」と入力します
Option server_side_encryption.
The server-side encryption algorithm used when storing this object in S3.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
 1 / None
   \ ()
 2 / AES256
   \ (AES256)
 3 / aws:kms
   \ (aws:kms)
server_side_encryption> 1

#KMSキーは使用しないため、「1」と入力します
Option sse_kms_key_id.
If using KMS ID you must provide the ARN of Key.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
 1 / None
   \ ()
 2 / arn:aws:kms:*
   \ (arn:aws:kms:us-east-1:*)
sse_kms_key_id> 1

#ストレージクラスはスタンダードを使用するため、「2」と入力します
Option storage_class.
The storage class to use when storing new objects in S3.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
~~省略~~
 2 / Standard storage class
   \ (STANDARD)
~~省略~~
storage_class> 2

#詳細設定は不要のため、「n」と入力します
Edit advanced config?
y) Yes
n) No (default)
y/n> n

#設定内容を確認し、誤りがなければ「y」と入力します
Configuration complete.
Options:
- type: s3
- provider: AWS
- access_key_id: (アクセスキー)
- secret_access_key: (シークレットアクセスキー)
- region: ap-northeast-1
- location_constraint: ap-northeast-1
- acl: private
- storage_class: STANDARD
Keep this "s3" remote?
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y

#S3が追加されていることを確認し、「q」を入力します
Current remotes:

Name                 Type
====                 ====
s3                  s3

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> q

設定ファイルは~/.config/rclone/rclone.confに格納されます。このような内容の設定ファイルができれいれば成功です。

[s3]
type = s3
provider = AWS
access_key_id = (アクセスキー)
secret_access_key = (シークレットアクセスキー)
region = ap-northeast-1
location_constraint = ap-northeast-1
acl = private
storage_class = STANDARD

上記でAmazon S3へのアクセスは可能になりました。動作確認としてrcloneコマンドを使用してファイル(./uploadtest1.txt)をS3(nm-test-rclone)にアップロードしてみましょう。

$ rclone copy ./uploadtest1.txt s3:nm-test-rclone

設定ファイルの作成② (Google Drive)

Amazon S3へのリモート設定が完了したら、次にGoogleドライブ(共有ドライブ)へのリモート設定を作成します。基本的にはS3と同じとなります。

$ rclone config

対話型で設定を進めていきます。

#新しいリモート設定を追加するため、「n」を入力します
Current remotes:

Name                 Type
====                 ====
s3                   s3

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> n

#リモート設定名に「google-drive」と入力します
Enter name for new remote.
name> google-drive

#ストレージ種別はGoogle Driveを選択するため、「18」と入力します
Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.

~~省略~~
18 / Google Drive
   \ (drive)
~~省略~~
Storage> 18

#認証情報はここでは不要のため、空欄のままエンターキーを押下します
Option client_id.
Google Application Client Id
Setting your own is recommended.
See https://rclone.org/drive/#making-your-own-client-id for how to create your own.
If you leave this blank, it will use an internal key which is low performance.
Enter a value. Press Enter to leave empty.
client_id> 

#認証情報はここでは不要のため、空欄のままエンターキーを押下します
Option client_secret.
OAuth Client Secret.
Leave blank normally.
Enter a value. Press Enter to leave empty.
client_secret> 

#rcloneのスコープはアプリケーションデータフォルダを除くすべてのファイルへのアクセスを許可するため、「1」と入力します
Option scope.
Scope that rclone should use when requesting access from drive.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
 1 / Full access all files, excluding Application Data Folder.
   \ (drive)
~~省略~~
scope> 1

#今回はSAを使用しないため、空欄のままエンターキーを押下します
Option service_account_file.
Service Account Credentials JSON file path.
Leave blank normally.
Needed only if you want use SA instead of interactive login.
Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`.
Enter a value. Press Enter to leave empty.
service_account_file> 

#詳細設定は不要のため、「n」と入力します
Edit advanced config?
y) Yes
n) No (default)
y/n> n

#自動設定を使用するため、「y」と入力します
Use auto config?
 * Say Y if not sure
 * Say N if you are working on a remote or headless machine

y) Yes (default)
n) No
y/n> y

#Googleアカウントの認証をするため、下記のリンクをブラウザで開いて認証します。
2022/10/14 10:44:06 NOTICE: If your browser doesn't open automatically go to the following link: http://127.0.0.1:53682/auth?state=XXXXXXXXXXXXXXXXXXXXXX
2022/10/14 10:44:06 NOTICE: Log in and authorize rclone for access
2022/10/14 10:44:06 NOTICE: Waiting for code...
2022/10/14 10:44:29 NOTICE: Got code

#共有ドライブの設定をするため、「y」と入力します
Configure this as a Shared Drive (Team Drive)?

y) Yes
n) No (default)
y/n> y

#共有ドライブ内の対象となるフォルダを選択します(今回は<code>案件資料フォルダ</code>が対象のため、「1」と入力します)
Option config_team_drive.
Shared Drive
Choose a number from below, or type in your own string value.
Press Enter for the default (0AIfPtc5MMK7TUk9PVA).
 1 / 案件資料フォルダ
   \ (フォルダID)
~~省略~~
config_team_drive> 1

#設定内容を確認し、誤りがなければ「y」と入力します
Configuration complete.
Options:
- type: drive
- scope: drive
- token: (アクセストークン)
- team_drive: (フォルダID)
- root_folder_id: 
Keep this "google-drive-a" remote?
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y

#google-driveが追加されていることを確認し、「q」を入力します
Current remotes:

Name                 Type
====                 ====
google-drive         drive
s3                   s3

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> q

~/.config/rclone/rclone.confに追記されていることを確認します。

[s3]
type = s3
provider = AWS
access_key_id = (アクセスキー)
secret_access_key = (シークレットアクセスキー)
region = ap-northeast-1
location_constraint = ap-northeast-1
acl = private
storage_class = STANDARD

[google-drive]
type: drive
scope: drive
token: (アクセストークン)
team_drive: (フォルダID)
root_folder_id:

上記でGoogleドライブへのアクセスは可能になりました。動作確認としてrcloneコマンドを使用してファイル(./uploadtest2.txt)をGoogleドライブ(共有ドライブ/案件資料フォルダ/フォルダ1)にアップロードしてみましょう。

$ rclone copy ./uploadtest2.txt google-drive:フォルダ1

動作確認

Googleドライブ→Amazon S3

ディレクトリ全体を同期するにはrcloneのサブコマンドであるsyncを使用します。対象のGoogleドライブのフォルダ(共有ドライブ/案件資料フォルダ/フォルダ1)をS3へ同期します。
※実際に同期する前に-nオプションと-vオプションを使い、DRY RUNしておくことをおすすめします。

$ rclone sync google-drive:フォルダ1 s3:nm-test-rclone

さいごに

今回はローカル端末にてrcloneを動かしましたが、今後はLambdaやコンテナなどAWS上で完結する実装を検討していきたいと思います。この記事がどなたかのお役に立てれば幸いです。

参考記事

こちらの記事を参考にさせていただきました
Amazon S3とGoogleドライブ間も同期できる! rcloneが超便利
RCLONE公式ドキュメント