本教學課程說明如何使用 Terraform,透過 Cloud Scheduler cron 工作建立及執行 Batch 工作。
Terraform 是一項開放原始碼工具,可讓您在設定檔中指定所需狀態,藉此佈建及管理基礎架構。這些檔案可視為程式碼,並儲存在 GitHub 等版本管控系統中。
雖然 Terraform 沒有 Batch 資源,但本教學課程會說明如何使用 Terraform 建立 Batch 工作。具體來說,您可以使用 Terraform 排定及執行 Cloud Scheduler Cron 工作,並指定 Batch API 建立及執行批次工作。Cloud Scheduler 是一項 Google Cloud 服務,可讓您自動排定 Cron 工作,並支援 Terraform。
本教學課程適用於已使用 Terraform 管理基礎架構,並想將 Batch 工作納入 Terraform 的 Batch 使用者。
目標
- 建立 Terraform 目錄和設定檔,定義會建立批次工作的 Cloud Scheduler Cron 工作。
- 部署 Terraform 設定,執行 Cron 工作。
- 確認 Cron 工作會建立批次工作。
- 更新 Terraform 設定,暫停 Cron 工作,停止建立批次工作。
費用
在本文件中,您會使用下列 Google Cloud計費元件:
您可以使用 Pricing Calculator,根據預測用量估算費用。
完成本文所述工作後,您可以刪除建立的資源,避免繼續計費,詳情請參閱「清除所用資源」。
事前準備
-
準備開發環境 (Cloud Shell 或本機殼層):
Cloud Shell
如要使用已設定 gcloud CLI 和 Terraform 的線上終端機,請啟用 Cloud Shell。
頁面底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。工作階段可能要幾秒鐘的時間才能初始化。
本機殼層
如要使用本機開發環境,請按照下列步驟操作:
-
安裝 Google Cloud CLI。
-
若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。
-
執行下列指令,初始化 gcloud CLI:
gcloud init - 安裝 Terraform。
-
-
選取或建立專案所需的角色
- 選取專案:選取專案時,不需具備特定 IAM 角色,只要您已獲派角色,即可選取任何專案。
-
建立專案:如要建立專案,您必須具備專案建立者角色 (
roles/resourcemanager.projectCreator),其中包含resourcemanager.projects.create權限。瞭解如何授予角色。
-
建立 Google Cloud 專案:
gcloud projects create PROJECT_ID
將
PROJECT_ID替換為您要建立的 Google Cloud 專案名稱。 -
選取您建立的 Google Cloud 專案:
gcloud config set project PROJECT_ID
將
PROJECT_ID替換為 Google Cloud 專案名稱。
-
確認 Google Cloud 專案已啟用計費功能。
-
啟用 Batch、Compute Engine、Cloud Logging、Cloud Scheduler 和 Resource Manager API (如有尚未啟用的 API):
啟用 API 所需的角色
如要啟用 API,您必須具備
serviceusage.services.enable權限。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過 Service Usage 管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。gcloud services enable batch.googleapis.com
compute.googleapis.com logging.googleapis.com cloudscheduler.googleapis.com cloudresourcemanager.googleapis.com -
確認專案至少有一個服務帳戶具備本教學課程所需的權限。
具體來說,您可以使用同一個服務帳戶或兩個不同的服務帳戶,授予下列權限:
- 允許 Cron 工作建立批次工作,並附加批次工作的服務帳戶。
- 允許批次工作建立及存取執行所需的資源。
為確保本教學課程的服務帳戶具備必要權限,可使用 Terraform 透過 Cloud Scheduler Cron 工作建立批次工作,請要求管理員將下列 IAM 角色授予本教學課程的服務帳戶:
- Cloud Scheduler cron 工作的服務帳戶:
-
Batch 工作的服務帳戶:
- 專案的批次工作代理程式回報者 (
roles/batch.agentReporter) - 專案的記錄寫入者 (
roles/logging.logWriter)
- 專案的批次工作代理程式回報者 (
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
-
確認您具備本教學課程所需的權限。
具體來說,您需要具備下列操作權限:
- 建立 Cron 工作,並附加 Cron 工作的服務帳戶。
- 檢視及刪除 Cron 工作和批次工作。
如要取得使用 Terraform 透過 Cloud Scheduler Cron 工作建立批次工作所需的權限,請要求管理員授予您下列 IAM 角色:
- Cloud Scheduler Cron 工作的服務帳戶服務帳戶使用者 (
roles/iam.serviceAccountUser) - 專案的 Cloud Scheduler 管理員 (
roles/cloudscheduler.admin) - 專案的批次工作編輯者 (
roles/batch.jobsEditor) - 專案的記錄檢視器 (
roles/logging.viewer)
建立 Terraform 目錄和設定檔
為 Terraform 建立目錄,並建立設定檔,定義要使用 Terraform 建立或更新的資源。本教學課程的範例設定檔定義了名為 batch-job-invoker 的 Cloud Scheduler cron 工作。啟用後,batch-job-invoker cron 工作每 5 分鐘會執行一次,建立定義的 Batch 工作新執行個體。
如要建立目錄,並在該目錄中建立新的 Terraform 設定 (
.tf) 檔案,請輸入下列指令,然後按下Enter:mkdir terraform && cd terraform && cat > main.tf這個指令會建立
terraform目錄,並將您導向該目錄,然後在下一行開始定義新的main.tf設定檔。複製並貼上下列 Terraform 設定:
# define variables variable "project_id" { type = string description = "The project name to use." default = "PROJECT_ID" } variable "project_number" { type = string description = "The project number to use." default = "PROJECT_NUMBER" } variable "region" { type = string description = "The region where resources are created." default = "us-central1" } variable "cloud_scheduler_service_account_email" { type = string description = "The service account email." default = "CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL" } variable "batch_service_account_email" { type = string description = "The service account email." default = "BATCH_SERVICE_ACCOUNT_EMAIL" } # define a Cloud Scheduler cron job which triggers Batch jobs resource "google_cloud_scheduler_job" "batch-job-invoker" { paused = false # this cron job is enabled name = "batch-job-invoker" project = var.project_id region = var.region schedule = "*/5 * * * *" # when enabled, run every 5 minutes time_zone = "America/Los_Angeles" attempt_deadline = "180s" retry_config { max_doublings = 5 max_retry_duration = "0s" max_backoff_duration = "3600s" min_backoff_duration = "5s" } # when this cron job runs, create and run a Batch job http_target { http_method = "POST" uri = "https://batch.googleapis.com/v1/projects/${var.project_id}/locations/${var.region}/jobs" headers = { "Content-Type" = "application/json" "User-Agent" = "Google-Cloud-Scheduler" } # Batch job definition body = base64encode(<<EOT { "taskGroups":[ { "taskSpec": { "runnables":{ "script": { "text": "echo Hello world! This job was created using Terraform and Cloud Scheduler." } } } } ], "allocationPolicy": { "serviceAccount": { "email": "${var.batch_service_account_email}" } }, "labels": { "source": "terraform_and_cloud_scheduler_tutorial" }, "logsPolicy": { "destination": "CLOUD_LOGGING" } } EOT ) oauth_token { scope = "https://www.googleapis.com/auth/cloud-platform" service_account_email = var.cloud_scheduler_service_account_email } } }更改下列內容:
PROJECT_ID:專案的專案 ID。PROJECT_NUMBER:專案的專案編號。CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL:您為 Cloud Scheduler Cron 工作準備的服務帳戶電子郵件地址。例如,如要使用 Compute Engine 預設服務帳戶,請指定下列項目:
PROJECT_NUMBER-compute@developer.gserviceaccount.comBATCH_SERVICE_ACCOUNT_EMAIL:您為批次工作準備的服務帳戶電子郵件地址。例如,如要使用 Compute Engine 預設服務帳戶,請指定下列項目:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
這項 Terraform 設定定義了一些輸入變數,以及一個會與 API 方法聯絡的 Cron 工作,用於建立批次工作。
如要儲存並關閉檔案,請按下
Ctrl+D(在 macOS 則為Command+D)。
部署 Terraform 設定,建立 Cron 工作
初始化 Terraform、產生預計變更,並套用這些變更,藉此部署 Terraform 設定。部署 Terraform 設定後,您可以說明專案中的資源,確認 Terraform 已成功建立 batch-job-invoker Cron 工作。
在目錄中初始化 Terraform:
terraform init輸出結果會與下列內容相似:
... Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. All Terraform commands should now work. If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary.根據專案和設定檔的目前狀態,產生 Terraform 執行計畫:
terraform plan輸出內容大致如下,顯示計畫是建立
batch-job-invokerCron 工作:Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # google_cloud_scheduler_job.batch-job-invoker will be created + resource "google_cloud_scheduler_job" "batch-job-invoker" { + id = (known after apply) + name = "batch-job-invoker" + paused = false + project = "PROJECT_ID" + region = "us-central1" + schedule = "*/5 * * * *" + state = (known after apply) + time_zone = "America/Los_Angeles" + http_target { + body = "..." + headers = { + "Content-Type" = "application/json" + "User-Agent" = "Google-Cloud-Scheduler" } + http_method = "POST" + uri = "https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs" + oauth_token { + scope = "https://www.googleapis.com/auth/cloud-platform" + service_account_email = "CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL" } } + retry_config { + max_backoff_duration = "3600s" + max_doublings = 5 + max_retry_duration = "0s" + min_backoff_duration = "5s" + retry_count = (known after apply) } } Plan: 1 to add, 0 to change, 0 to destroy. ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.如要套用方案來建立
batch-job-invokerCron 工作,請按照下列步驟操作:輸入下列指令:
terraform apply輸出內容與先前的
terraform plan指令類似,但結尾會顯示確認提示。如要確認並套用計畫,請輸入
yes。輸出結果會與下列內容相似:
google_cloud_scheduler_job.batch-job-invoker: Creating... google_cloud_scheduler_job.batch-job-invoker: Creation complete after 0s [id=projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
如要確認
batch-job-invokerCron 工作是否存在且已啟用,請說明該工作:gcloud scheduler jobs describe batch-job-invoker --location us-central1輸出結果會與下列內容相似:
attemptDeadline: 180s httpTarget: body: ... headers: Content-Type: application/json User-Agent: Google-Cloud-Scheduler httpMethod: POST oauthToken: scope: https://www.googleapis.com/auth/cloud-platform serviceAccountEmail: CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL uri: https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs lastAttemptTime: '...' name: projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker retryConfig: maxBackoffDuration: 3600s maxDoublings: 5 maxRetryDuration: 0s minBackoffDuration: 5s schedule: '*/5 * * * *' scheduleTime: '...' state: ENABLED status: {} timeZone: America/Los_Angeles userUpdateTime: '...'在輸出內容中,確認
state欄位已設為ENABLED。
確認 Cron 工作會建立批次工作
確認 batch-job-invoker Cron 工作是否正確建立批次工作。
請等待 5 分鐘,讓 Cron 工作自動執行,或觸發 Cron 工作立即執行:
gcloud scheduler jobs run batch-job-invoker --location us-central1列出由
batch-job-invokerCron 工作建立的批次工作:gcloud batch jobs list \ --filter labels.source=\"terraform_and_cloud_scheduler_tutorial\" \ --sort-by ~createTime--filter labels.source=\"terraform_and_cloud_scheduler_tutorial\"旗標會篩選清單,只納入標籤鍵為source、值為terraform_and_cloud_scheduler_tutorial的 Batch 工作。--sort-by ~createTime旗標會將清單由新到舊排序。
更新 Terraform 設定,暫停 Cron 工作
達到所需的批次工作數量後,請更新並部署 Terraform 設定,暫停 batch-job-invoker Cron 工作。如要更新 Cron 工作或其他批次工作的其他屬性,也適用相同程序。
更新 Terraform 設定檔,將
paused欄位設為true,暫停 Cron 工作:sed -i 's/paused = false # this cron job is enabled/paused = true # this cron job is paused/g' main.tf根據專案和設定檔的目前狀態,產生 Terraform 執行計畫:
terraform plan輸出內容大致如下,顯示計畫將
paused欄位的值從false更新為true:google_cloud_scheduler_job.batch-job-invoker: Refreshing state... [id=projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: # google_cloud_scheduler_job.batch-job-invoker will be updated in-place ~ resource "google_cloud_scheduler_job" "batch-job-invoker" { id = "projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker" name = "batch-job-invoker" ~ paused = false -> true # (6 unchanged attributes hidden) ~ http_target { ~ headers = { + "User-Agent" = "Google-Cloud-Scheduler" # (1 unchanged element hidden) } # (3 unchanged attributes hidden) # (1 unchanged block hidden) } # (1 unchanged block hidden) } Plan: 0 to add, 1 to change, 0 to destroy. ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.如要套用計畫來更新
batch-job-invokerCron 工作,請按照下列步驟操作:輸入下列指令:
terraform apply輸出內容與先前的
terraform plan指令類似,但結尾會顯示確認提示。如要確認並套用計畫,請輸入
yes。輸出結果會與下列內容相似:
google_cloud_scheduler_job.batch-job-invoker: Modifying... [id=projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker] google_cloud_scheduler_job.batch-job-invoker: Modifications complete after 1s [id=projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker] Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
如要確認
batch-job-invokerCron 工作是否已暫停,請執行下列指令:gcloud scheduler jobs describe batch-job-invoker --location us-central1輸出結果會與下列內容相似:
attemptDeadline: 180s httpTarget: body: ... headers: Content-Type: application/json User-Agent: Google-Cloud-Scheduler httpMethod: POST oauthToken: scope: https://www.googleapis.com/auth/cloud-platform serviceAccountEmail: CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL uri: https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs lastAttemptTime: '...' name: projects/PROJECT_ID/locations/us-central1/jobs/batch-job-invoker retryConfig: maxBackoffDuration: 3600s maxDoublings: 5 maxRetryDuration: 0s minBackoffDuration: 5s schedule: '*/5 * * * *' scheduleTime: '...' state: PAUSED status: {} timeZone: America/Los_Angeles userUpdateTime: '...'在輸出內容中,確認
state欄位已設為PAUSED。
清除所用資源
為避免因為本教學課程所用資源,導致系統向 Google Cloud 收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。
刪除專案
刪除 Google Cloud 專案:
gcloud projects delete PROJECT_ID
前往上層目錄,然後刪除 Terraform 目錄及其所有檔案。
cd .. && rm -r terraform
刪除個別資源
刪除
batch-job-invokerCron 工作。terraform destroy如要刪除本教學課程中的所有批次工作,請按照下列步驟操作:
列出由
batch-job-invokerCron 工作建立的所有批次工作:gcloud batch jobs list \ --filter labels.source=\"terraform_and_cloud_scheduler_tutorial\" \ --sort-by ~createTime記下要刪除的各項工作名稱。
刪除本教學課程中的批次工作:
gcloud batch jobs delete JOB_NAME --location us-central1將
JOB_NAME替換為批次工作的名稱。對所有批次工作重複這個步驟。
如果您為本教學課程建立了服務帳戶,請刪除該服務帳戶:
gcloud iam service-accounts delete SERVICE_ACCOUNT_EMAIL將
SERVICE_ACCOUNT_EMAIL替換為您為本教學課程建立的服務帳戶電子郵件地址。也就是說,您使用了下列服務帳戶:CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL:Cloud Scheduler 的服務帳戶。BATCH_SERVICE_ACCOUNT_EMAIL:Batch 的服務帳戶。
如果您建立了兩個不同的服務帳戶,請重複這個步驟。
前往上層目錄,然後刪除 Terraform 目錄及其所有檔案。
cd .. && rm -r terraform
後續步驟
- 進一步瞭解如何搭配使用 Terraform 和 Google Cloud:
- 進一步瞭解 Cloud Scheduler cron 工作。
- 進一步瞭解批次工作。