要將 EC2 上的資料庫自動備份,主要可以分為四個步驟
- 申請 Google OAuth2.0 驗證
- rclone 遠端儲存配置
- Shell Script 備份指令
- cron 排程設定
申請 Google OAuth.0 驗證
- Google Developers Console 建立專案
- API 和服務頁面,搜尋 Google Drive API
- OAuth 同意畫面,User Type 選外部
- 都設定好後,回到 OAuth 同意畫面,可以看到發布狀態,按發布應用程式
- 憑證頁面,點擊創建憑證,選擇 OAuth 客戶端 ID ,應用類型選擇電腦版應用程式
- 記錄下生成的「客戶端 ID」和「客戶端密鑰」。
rclone 遠端儲存配置
- 安裝 rclone
curl https://rclone.org/install.sh | sudo bash
- 配置 rclone config 文件
rclone config
- n) New remote 新建遠端儲存配置
- Enter name for new remote.
name> 輸入遠端儲存名稱
- Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
可以看到 17 Google Drive輸入 17
- 接下來要輸入
client_id 輸入剛剛申請的GOOGLE 客戶端 ID
client_secret 輸入剛剛申請的GOOGLE 客戶端密鑰 - Option scope.
Comma separated list of scopes 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.選擇1 完全訪問權限
- 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>直接按 enter 也就是用 OAuth2.0 授權
- 接下來選項就是有 default 選 default
- 接下來這步驟就是要驗證,選 N,因為 EC2 沒有瀏覽器可以驗證,所以要用自己本機驗證
Use web browser to automatically authenticate rclone with remote?
Say Y if the machine running rclone has a web browser you can use
Say N if running rclone on a (remote) machine without web browser access
If not sure try Y. If Y failed, try N.
y) Yes (default)
n) Noy/n> N
- 將以下指令貼在本機終端機,就會拿到 token 再複製下來貼到 EC2
rclone authorize "drive" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
- 檢查是否設定成功
有看到.pem就是成功了rclone ls 剛剛設定的遠端儲存名稱:
Shell Script 備份指令
寫個 Shell 檔,這邊資料庫主要是使用 Docker 部屬
#!/bin/bash #備份資料庫 docker exec 容器名稱 pg_dump -U postgres -d 資料庫名稱 > 備份檔名稱.sql #上傳到 Google Drive 根目錄 rclone copy 備份檔名稱.sql 遠端儲存名稱: -v echo "備份以及上傳成功!!!"
- 測試看看能不能執行
bash Shell檔案名稱.sh
cron 排程設定
- 開啟權限
chmod +x Shell檔案名稱.sh
- 編輯 cron 工作
crontab -e
- 備份腳本每天兩點執行(路徑就看 Shell 檔放哪裡)
0 2 * * * /bin/bash /home/ubuntu/Shell檔案名稱.sh
- 確認排程,這邊可以看到剛剛設定的腳本
crontab -l
- 改 EC2 時區為台北時間
sudo timedatectl set-timezone Asia/Taipei