Questo tutorial spiega come utilizzare Terraform per creare ed eseguire job Batch utilizzando un cron job Cloud Scheduler.
Terraform è uno strumento open source che consente di eseguire il provisioning e gestire l'infrastruttura specificando lo stato desiderato nei file di configurazione. Questi file possono essere trattati come codice e archiviati in sistemi di controllo della versione come GitHub.
Anche se Terraform non dispone di risorse per Batch, questo tutorial mostra come utilizzare Terraform per creare job Batch. In particolare, puoi utilizzare Terraform per pianificare ed eseguire un cron job di Cloud Scheduler che ha come target l'API Batch per creare ed eseguire job Batch. Cloud Scheduler è un servizio Google Cloud che consente di pianificare automaticamente i cron job e supporta Terraform.
Questo tutorial è destinato agli utenti di Batch che gestiscono già l'infrastruttura con Terraform e vogliono incorporare i job Batch in Terraform.
Crea la directory e il file di configurazione Terraform
Crea una directory per Terraform e un file di configurazione
che definisce le risorse che vuoi creare o aggiornare utilizzando Terraform.
Il file di configurazione di esempio per questo tutorial definisce un
cron job Cloud Scheduler denominato batch-job-invoker
.
Quando è abilitato, il cron job batch-job-invoker
viene eseguito ogni 5 minuti per creare una nuova istanza del job Batch
definito.
Per creare una directory e un nuovo file di configurazione Terraform (
.tf
) al suo interno, digita il comando seguente e poi premiEnter
:mkdir terraform && cd terraform && cat > main.tf
Questo comando crea la directory
terraform
, ti porta al suo interno e inizia a definire un nuovo file di configurazionemain.tf
nella riga successiva.Copia e incolla la seguente configurazione 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 } } }
Sostituisci quanto segue:
PROJECT_ID
: l'ID progetto del tuo progetto.PROJECT_NUMBER
: il numero di progetto del tuo progetto.CLOUD_SCHEDULER_SERVICE_ACCOUNT_EMAIL
: l'indirizzo email del account di servizio che hai preparato per il job cron di Cloud Scheduler.Ad esempio, per utilizzare l'account di servizio predefinito di Compute Engine, specifica quanto segue:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
BATCH_SERVICE_ACCOUNT_EMAIL
: l'indirizzo email delaccount di serviziot che hai preparato per i job batch.Ad esempio, per utilizzare l'account di servizio predefinito di Compute Engine, specifica quanto segue:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
Questa configurazione Terraform definisce alcune variabili di input e un job cron che contatta il metodo API per creare un job Batch.
Per salvare e chiudere il file, premi
Ctrl+D
(oCommand+D
su macOS).
Esegui il deployment della configurazione Terraform per creare il cron job
Esegui il deployment della configurazione Terraform inizializzando Terraform, generando
le modifiche pianificate e applicandole. Dopo aver eseguito il deployment della configurazione Terraform, puoi descrivere le risorse nel tuo progetto per verificare che Terraform abbia creato correttamente il job cron batch-job-invoker
.
Inizializza Terraform nella directory:
terraform init
L'output è simile al seguente:
... 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.
Genera il piano di esecuzione Terraform in base allo stato attuale del tuo progetto e al file di configurazione:
terraform plan
L'output è simile al seguente, che mostra che il piano prevede di creare il job cron
batch-job-invoker
: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.
Per applicare il piano per creare il job cron
batch-job-invoker
:Inserisci questo comando:
terraform apply
L'output è simile al comando
terraform plan
precedente, tranne che termina con una richiesta di conferma.Per confermare e applicare il piano, inserisci
yes
.L'output è simile al seguente:
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.
Per verificare che il job cron
batch-job-invoker
esista e sia abilitato, descrivilo:gcloud scheduler jobs describe batch-job-invoker --location us-central1
L'output è simile al seguente:
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: '...'
Nell'output, verifica che il campo
state
sia impostato suENABLED
.
Verifica che il job cron crei un job Batch
Verifica che il job cron batch-job-invoker
crei correttamente i job batch.
Attendi 5 minuti che il cron job venga eseguito automaticamente o attiva l'esecuzione immediata del cron job:
gcloud scheduler jobs run batch-job-invoker --location us-central1
Elenca i job Batch creati dal cron job
batch-job-invoker
:gcloud batch jobs list \ --filter labels.source=\"terraform_and_cloud_scheduler_tutorial\" \ --sort-by ~createTime
- Il flag
--filter labels.source=\"terraform_and_cloud_scheduler_tutorial\"
filtra l'elenco in modo da includere solo i job batch che hanno un'etichetta con la chiavesource
e il valoreterraform_and_cloud_scheduler_tutorial
. - Il flag
--sort-by ~createTime
ordina l'elenco dal più recente al meno recente.
- Il flag
Aggiorna la configurazione Terraform per sospendere il cron job
Una volta raggiunto il numero desiderato di job Batch,
aggiorna ed esegui il deployment della configurazione Terraform per mettere in pausa il
cron job batch-job-invoker
. Se vuoi aggiornare altre proprietà del
cron job o dei batch job futuri,
si applica lo stesso processo.
Aggiorna il file di configurazione Terraform per sospendere il cron job impostando il campo
paused
sutrue
:sed -i 's/paused = false # this cron job is enabled/paused = true # this cron job is paused/g' main.tf
Genera il piano di esecuzione Terraform in base allo stato attuale del tuo progetto e al file di configurazione:
terraform plan
L'output è simile al seguente, che mostra che il piano prevede di aggiornare il valore del campo
paused
dafalse
atrue
: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.
Per applicare il piano per aggiornare il job cron
batch-job-invoker
:Inserisci questo comando:
terraform apply
L'output è simile al comando
terraform plan
precedente, tranne che termina con una richiesta di conferma.Per confermare e applicare il piano, inserisci
yes
.L'output è simile al seguente:
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.
Per verificare che il job cron
batch-job-invoker
sia in pausa, descrivilo:gcloud scheduler jobs describe batch-job-invoker --location us-central1
L'output è simile al seguente:
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: '...'
Nell'output, verifica che il campo
state
sia impostato suPAUSED
.