概要
前回に引き続きTeraformの学習メモ
今回の目標は「Cloud Runを作成して、それをSchedulerから動かす」
手順
サービスアカウントとIAMを作成
Cloud Run本体と、Scheduler用の2つを用意する。
resource "google_service_account" "example_cloudrun_sa" {
project = var.project_id
account_id = "example-cr-sa"
display_name = "Example Cloud Run Service Account"
}
resource "google_service_account" "example_invoker_sa" {
project = var.project_id
account_id = "example-invoker-sa"
display_name = "Example Invoker Service Account"
}
resource "google_project_iam_member" "example_cloudrun_sa_roles" {
for_each = local.example_cloudrun_sa_roles
project = var.project_id
role = each.key
member = "serviceAccount:${google_service_account.example_cloudrun_sa.email}"
}
resource "google_project_iam_member" "example_invoker_sa_roles" {
for_each = local.example_invoker_sa_roles
project = var.project_id
role = each.key
member = "serviceAccount:${google_service_account.example_invoker_sa.email}"
}
Cloud Runを作成する
resource "google_cloud_run_v2_service" "example_service" {
provider = google-beta
name = "example-data-service"
location = var.region
project = var.project_id
ingress = "INGRESS_TRAFFIC_ALL"
deletion_protection = var.deletion_protection_cloud_run_service
template {
containers {
image = var.example_service_image_uri
ports {
container_port = 8080
}
# Cloud Runの環境変数を設定する
env {
name = "ENV"
value = var.environment_name
}
env {
name = "DB_USER"
value = var.db_user_id
}
# シークレットを使う場合
env {
name = "DB_PASSWORD"
value_source {
secret_key_ref {
secret = "db-password"
version = "latest"
}
}
}
}
service_account = var.example_cloudrun_sa_email
# 今回別モジュールでservice accountを定義したので変数で受け取っているが
# 同モジュールで定義されているなら以下のように書ける。
# service_account = google_service_account.example_cloudrun_sa.email
# DBアクセスのためにVPC Egressが必須
vpc_access {
network_interfaces {
network = var.vpc_network_id
subnetwork = var.vpc_subnetwork_id
tags = ["cloudrun-direct-vpc-egress"]
}
egress = "ALL_TRAFFIC"
}
}
traffic {
type = "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST"
percent = 100
}
}
Schedulerを作る
resource "google_cloud_scheduler_job" "example_job" {
name = "example-job"
description = "Example Job"
schedule = var.example_scheduler_cron
time_zone = "Asia/Tokyo"
http_target {
http_method = "POST"
uri = "${google_cloud_run_v2_service.example_service.uri}/example"
oidc_token {
service_account_email = var.example_invoker_sa_email
}
}
retry_config {
retry_count = 3
max_retry_duration = "300s"
min_backoff_duration = "10s"
max_backoff_duration = "60s"
max_doublings = 3
}
}