本教學課程說明如何使用 Cloud Scheduler 和 Cloud Run 函式,排定 Filestore 執行個體的備份作業。
如要瞭解如何使用代管服務排程器建立備份,請參閱「Filestore 進階級備份」。
目標
- 為 Cloud Scheduler 建立用戶端服務帳戶,該帳戶必須具備叫用 Cloud Run 函式所需的憑證。
- 為 Cloud Run 函式建立用戶端服務帳戶,該帳戶具有呼叫 Filestore 端點的憑證。
- 建立 Cloud Run 函式,用於建立 Filestore 執行個體的備份。
- 建立 Cloud Run functions 函式,刪除 Filestore 執行個體的備份。
- 建立 Cloud Scheduler 工作,定期執行任一函式。
費用
在本文件中,您將使用下列 Google Cloud計費元件:
- Artifact Registry API
- Cloud Build API
- Filestore API
- Cloud Functions API
- Cloud Logging API
- Pub/Sub API
- Cloud Run Admin API
- Cloud Scheduler API
如要根據預測用量估算費用,請使用 Pricing Calculator。
事前準備
- 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自體驗產品的實際應用成效。新客戶還能獲得價值 $300 美元的免費抵免額,能用於執行、測試及部署工作負載。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Build, Filestore, Cloud Run functions, Cloud Logging, Pub/Sub, Cloud Run, and Cloud Scheduler APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Build, Filestore, Cloud Run functions, Cloud Logging, Pub/Sub, Cloud Run, and Cloud Scheduler APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init - 如果專案中沒有 Filestore 執行個體,請先建立一個。
為 Cloud Scheduler 和 Cloud Run functions 建立用戶端服務帳戶
如果尚未啟用,請在控制台中點選「啟用 Cloud Shell」 Google Cloud 。
建立用戶端服務帳戶,Cloud Scheduler 會以該帳戶身分執行,叫用 Cloud Run functions 函式。在本範例中,請使用
iam service-accounts create命令將帳戶命名為schedulerunner,並將顯示名稱設為「Service Account for FS Backups-Scheduler」:gcloud iam service-accounts create schedulerunner \ --display-name="Service Account for FS Backups-Scheduler"建立用戶端服務帳戶,讓 Cloud Run 函式以該帳戶身分執行,藉此呼叫 Filestore 端點。在本範例中,我們將帳戶命名為
backupagent,並將顯示名稱設為「Service Account for FS Backups-GCF」:gcloud iam service-accounts create backupagent \ --display-name="Service Account for FS Backups-GCF"您可以執行
iam service-accounts list指令,檢查服務帳戶是否已建立:gcloud iam service-accounts list指令會傳回類似下列內容:
NAME EMAIL DISABLED Service Account for FS Backups-GCF backupagent@$PROJECT_ID.iam.gserviceaccount.com False Service Account for FS Backups-Scheduler schedulerunner@$PROJECT_ID.iam.gserviceaccount.com False
設定環境變數
在本機環境中設定下列環境變數:
Google Cloud 專案 ID 和專案:
export PROJECT_ID=`gcloud config get-value core/project` export PROJECT_NUMBER=`gcloud projects describe $PROJECT_ID --format="value(projectNumber)"`Cloud Scheduler 服務代理程式和 Cloud Scheduler 與 Cloud Run 函式的用戶端服務帳戶:
export SCHEDULER_SA=service-$PROJECT_NUMBER@gcp-sa-cloudscheduler.iam.gserviceaccount.com export SCHEDULER_CLIENT_SA=schedulerunner@$PROJECT_ID.iam.gserviceaccount.com export GCF_CLIENT_SA=backupagent@$PROJECT_ID.iam.gserviceaccount.com您的 Filestore 執行個體:
export SOURCE_INSTANCE_LOCATION=fs-location export SOURCE_INSTANCE_NAME=instance-id export SHARE_NAME=file-share-name更改下列內容:
- fs-location,並將其替換為來源 Filestore 執行個體所在的可用區或區域。
- instance-id,並提供來源 Filestore 執行個體的執行個體 ID。
- file-share-name,並指定從執行個體提供的 NFS 檔案共用名稱。
為 Filestore 備份設定環境變數:
export BACKUP_REGION=backup-region將 backup-region 替換為要儲存備份的區域。
建立可建立備份的函式
前往 Google Cloud 控制台的 Cloud Run functions 頁面。
按一下「Write a function」(編寫函式),然後設定函式,如下所示:
- 設定:
- 服務名稱:在本範例中,我們將函式命名為
fsbackup。 - 區域:在本範例中,請選取
us-central1。 - 執行階段:從選單中選取Cloud Run functions 完全支援的任何 Python 3 執行階段。
- 服務名稱:在本範例中,我們將函式命名為
- 觸發條件:
- 這個範例不需要設定觸發條件。
- 驗證:選取
Require authentication。 - 「Ingress」(輸入):選取
All。 - 容器、磁碟區、網路、安全性
- 前往「安全性」分頁,然後從選單中選取
Service Account for FS Backups-GCF(backupagent@$PROJECT_ID.iam.gserviceaccount.com)。
- 前往「安全性」分頁,然後從選單中選取
- 設定:
按一下「建立」,然後繼續進行下列設定:
- 函式進入點:輸入
create_backup。 在
requirements.txt檔案中新增下列依附元件:functions-framework==3.* google-auth==2.29.0 requests==2.31.0視應用情況而定,您可能需要指定其他依附元件及其對應的版本號碼。詳情請參閱「預先安裝的套件」。
使用內嵌編輯器,將下列 Python 程式碼範例複製到
main.py檔案中:建立備份
這個程式碼範例會建立名為
mybackup-的備份,並附加建立時間。PROJECT_ID = 'project-id' SOURCE_INSTANCE_LOCATION = 'fs-location' SOURCE_INSTANCE_NAME = 'instance-id' SOURCE_FILE_SHARE_NAME = 'file-share-name' BACKUP_REGION = 'backup-region' import functions_framework import google.auth import google.auth.transport.requests from google.auth.transport.requests import AuthorizedSession import time import requests import json credentials, project = google.auth.default() auth_request = google.auth.transport.requests.Request() credentials.refresh(auth_request) authed_session = AuthorizedSession(credentials) def get_backup_id(): return "mybackup-" + time.strftime("%Y%m%d-%H%M%S") @functions_framework.http def create_backup(request): trigger_run_url = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups?backupId={}".format(PROJECT_ID, BACKUP_REGION, get_backup_id()) headers = { 'Content-Type': 'application/json' } post_data = { "description": "my new backup", "source_instance": "projects/{}/locations/{}/instances/{}".format(PROJECT_ID, SOURCE_INSTANCE_LOCATION, SOURCE_INSTANCE_NAME), "source_file_share": "{}".format(SOURCE_FILE_SHARE_NAME) } print("Making a request to " + trigger_run_url) r = authed_session.post(url=trigger_run_url, headers=headers, data=json.dumps(post_data)) data = r.json() print(data) if r.status_code == requests.codes.ok: print(str(r.status_code) + ": The backup is uploading in the background.") else: raise RuntimeError(data['error']) return "Backup creation has begun!"更改下列內容:
- project-id,並將 Google Cloud 來源 Filestore 執行個體的專案 ID 填入其中。
- fs-location,與來源 Filestore 執行個體的區域或可用區相同。
- instance-id,並將其替換為來源 Filestore 執行個體名稱。
- 將 file-share-name 替換成檔案共用區的名稱。
- backup-region,並指定備份儲存區域。
按一下「測試」
Cloud Shell 會在新分頁中開啟工作階段。如果成功,會傳回下列訊息:
Backup creation has begun!按一下「儲存並重新部署」,然後等待部署作業完成。
切換回先前的 Cloud Shell 分頁。
刪除備份
這段程式碼範例會刪除超過預先定義時間範圍的備份。
一次只能刪除每個來源執行個體的一項備份。詳情請參閱「備份」。
設定這個函式的方式與您用來建立備份的函式相同,但需進行下列修改:
- 函式名稱:
deletefsbackup。 - 進入點:
delete_backup。
PROJECT_ID = 'project-id' BACKUP_REGION = 'region' BACKUP_RETENTION_TIME_HRS = hours import functions_framework import google.auth import google.auth.transport.requests from google.auth.transport.requests import AuthorizedSession import time import requests import json credentials, project = google.auth.default() auth_request = google.auth.transport.requests.Request() credentials.refresh(auth_request) authed_session = AuthorizedSession(credentials) retention_seconds = BACKUP_RETENTION_TIME_HRS * 60 * 60 @functions_framework.http def delete_backup(request): now = time.time() backup_list = [] trigger_run_url = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups".format(PROJECT_ID, BACKUP_REGION) r = authed_session.get(trigger_run_url) data = r.json() if not data: print("No backups to delete.") return "No backups to delete." else: backup_list.extend(data['backups']) while "nextPageToken" in data.keys(): nextPageToken = data['nextPageToken'] trigger_run_url_next = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups?pageToken={}".format(PROJECT_ID, BACKUP_REGION, nextPageToken) r = authed_session.get(trigger_run_url_next) data = r.json() backup_list.extend(data['backups']) for i in backup_list: backup_time = i['createTime'] backup_time = backup_time[:-4] backup_time = float(time.mktime(time.strptime(backup_time, "%Y-%m-%dT%H:%M:%S.%f"))) i['backup_timestamp'] = backup_time sorted_backup_list = sorted(backup_list, key=lambda d: d['backup_timestamp']) oldest_backup = sorted_backup_list[0] if now - oldest_backup['backup_timestamp'] > retention_seconds: print(oldest_backup['name'] + " is older than the indicated retention time.") r = authed_session.delete("https://file.googleapis.com/v1/{}".format(oldest_backup['name'])) data = r.json() print(data) if r.status_code == requests.codes.ok: print(str(r.status_code) + ": Deleting " + oldest_backup['name'] + " in the background.") else: raise RuntimeError(data['error']) return "Backup deletion has begun!" return "All backups are within the indicated retention period."更改下列內容:
- project-id 替換為備份的 Google Cloud 專案 ID。
- 將 region 替換為備份所在的區域。備份、排程器工作和函式都應位於相同位置。
- hours,並指定備份保留時數。舉例來說,如要保留備份 10 天,請輸入
240。
- 函式進入點:輸入
將 IAM 角色指派給用戶端服務帳戶
將 Cloud Scheduler 服務代理程式新增至 Cloud Scheduler 用戶端服務帳戶的 IAM 政策,並指派
roles/cloudscheduler.serviceAgent角色。這樣一來,服務代理就能模擬用戶端服務帳戶,叫用建立備份的函式。執行iam service-accounts add-iam-policy-binding指令:gcloud iam service-accounts add-iam-policy-binding $SCHEDULER_CLIENT_SA \ --member=serviceAccount:$SCHEDULER_SA \ --role=roles/cloudscheduler.serviceAgent將
roles/file.editor角色授予 Cloud Run functions 的用戶端服務帳戶,該帳戶才能呼叫 Filestore 端點。執行projects add-iam-policy-binding指令:gcloud projects add-iam-policy-binding $PROJECT_ID \ --member=serviceAccount:$GCF_CLIENT_SA \ --role=roles/file.editor將 Cloud Scheduler 的用戶端服務帳戶的
roles/run.invoker角色授予要使用的函式。執行下列run services add-iam-policy-binding指令:建立備份
gcloud run services add-iam-policy-binding fsbackup \ --member serviceAccount:$SCHEDULER_CLIENT_SA \ --role roles/run.invoker \ --region=us-central1現在只有 Cloud Scheduler 的用戶端服務帳戶可以叫用
fsbackup。刪除備份
gcloud run services add-iam-policy-binding deletefsbackup \ --member serviceAccount:$SCHEDULER_CLIENT_SA \ --role roles/run.invoker現在只有 Cloud Scheduler 的用戶端服務帳戶可以叫用
deletefsbackup。
建立 Cloud Scheduler 工作,在指定時間觸發函式
建立備份
在本教學課程的範例中,如果您想在每個工作日的晚上 10 點安排備份,請使用
scheduler jobs create http指令:gcloud scheduler jobs create http fsbackupschedule \ --schedule "0 22 * * 1-5" \ --http-method=GET \ --uri=https://fsbackup-$PROJECT_NUMBER.us-central1.run.app \ --oidc-service-account-email=$SCHEDULER_CLIENT_SA \ --location=us-central1--schedule旗標可讓您使用 unix-cron 格式指定工作執行頻率。詳情請參閱「設定 Cron 工作時間表」。每個例項每小時最多可建立六個備份。
啟動上一個步驟中建立的 Cloud Scheduler 工作。在我們的範例中,請使用
scheduler jobs runs指令立即執行:gcloud scheduler jobs run fsbackupschedule執行指令後,
fsbackupschedule工作會立即叫用fsbackup函式,然後在工作暫停前,每週一到週五晚上 10 點再次叫用該函式。檢查
fsbackup函式的記錄,確認函式是否正常執行並傳回status 200。如要在 Google Cloud 控制台中查看記錄,請使用 Logs Explorer:
-
前往 Google Cloud 控制台的 「Logs Explorer」頁面:
如果您是使用搜尋列尋找這個頁面,請選取子標題為「Logging」的結果。
「Query results」(查詢結果) 窗格會顯示最近的記錄檔。
-
使用
backups list指令檢查現有備份的狀態:gcloud filestore backups list指令會傳回類似下列內容:
NAME LOCATION SRC_INSTANCE SRC_FILE_SHARE STATE mybackup-20201123-184500 us-central1 us-central1-c/instances/nfs-server vol1 READY
刪除備份
以本教學課程的範例來說,如要安排作業在每個工作日的晚上 10 點刪除備份,請使用
scheduler jobs create http指令:gcloud scheduler jobs create http deletefsbackupschedule \ --schedule "0 22 * * 1-5" \ --http-method=GET \ --uri=https://us-central1-$PROJECT_ID.cloudfunctions.net/deletefsbackup \ --oidc-service-account-email=$SCHEDULER_CLIENT_SA \ --oidc-token-audience=https://us-central1-$PROJECT_ID.cloudfunctions.net/deletefsbackup--schedule旗標可讓您使用 unix-cron 格式指定工作執行頻率。詳情請參閱「設定 Cron 工作時間表」。與相同來源執行個體相關聯的備份
delete作業必須一次執行一個。詳情請參閱「備份」。啟動上一個步驟中建立的 Cloud Scheduler 工作。在我們的範例中,我們使用
scheduler jobs runs指令立即執行:gcloud scheduler jobs run deletefsbackupschedule執行指令後,
deletefsbackupschedule工作會立即叫用deletefsbackup函式,然後在工作暫停前,每週一到週五晚上 10 點再次叫用該函式。檢查
deletefsbackup函式的記錄,確認函式是否正常執行並傳回status 200。如要在 Google Cloud 控制台中查看記錄,請使用 Logs Explorer:
-
前往 Google Cloud 控制台的 「Logs Explorer」頁面:
如果您是使用搜尋列尋找這個頁面,請選取子標題為「Logging」的結果。
「Query results」(查詢結果) 窗格會顯示最近的記錄檔。
-
使用
backups list指令檢查現有備份的狀態:gcloud filestore backups list指令會傳回類似下列內容:
NAME LOCATION SRC_INSTANCE SRC_FILE_SHARE STATE mybackup-20201123-184500 us-central1 us-central1-c/instances/nfs-server vol1 READY
備份配額不足警示
如果排定備份作業可能會導致備份配額用盡,建議您設定備份配額不足警告。這樣一來,當備份配額即將用盡時,您就會收到通知。
清除所用資源
完成教學課程後,您可以清除所建立的資源,這樣資源就不會繼續使用配額,也不會產生費用。下列各節將說明如何刪除或關閉這些資源。
刪除專案
如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。
刪除專案的方法如下:
- 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。
- 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
- 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。
後續步驟
- 瞭解 Filestore 快照。
- 進一步瞭解 Filestore 備份。
- 瞭解如何安排 Filestore Enterprise 快照。