Skip to content

Instantly share code, notes, and snippets.

@mizzy
Last active February 27, 2025 07:02
Show Gist options
  • Save mizzy/64696039c270bed7665dc832e2c06273 to your computer and use it in GitHub Desktop.
Save mizzy/64696039c270bed7665dc832e2c06273 to your computer and use it in GitHub Desktop.
Send mails by Cloud Run functions
resource "google_service_account" "send_mail" {
account_id = "send-mail"
display_name = "send-mail"
}
resource "google_project_iam_member" "send_mail" {
for_each = toset([
"roles/iam.serviceAccountTokenCreator",
])
project = data.google_project.current.project_id
member = "serviceAccount:${google_service_account.send_mail.email}"
role = each.value
}
resource "google_storage_bucket" "function_source" {
name = "function-source"
location = "asia-northeast1"
}
data "archive_file" "send_mail" {
source_dir = "functions/send_mail/"
output_path = "send-mail.zip"
type = "zip"
}
resource "google_storage_bucket_object" "send_mail" {
name = "send-mail-${data.archive_file.send_mail.output_md5}.zip"
bucket = google_storage_bucket.function_source.name
source = data.archive_file.send_mail.output_path
}
resource "google_pubsub_topic" "send_mail" {
name = "send-mail"
}
resource "google_cloud_scheduler_job" "send_mail" {
name = "send-mail"
schedule = "*/5 * * * *"
time_zone = "Asia/Tokyo"
region = "asia-northeast1"
pubsub_target {
topic_name = google_pubsub_topic.send_mail.id
data = base64encode(jsonencode({
service_account = google_service_account.send_mail.email
user_email = "[email protected]"
destination_email = "[email protected]"
}))
}
}
resource "google_cloudfunctions2_function" "send_mail" {
name = "send-mail"
location = "asia-northeast1"
event_trigger {
trigger_region = "asia-northeast1"
event_type = "google.cloud.pubsub.topic.v1.messagePublished"
pubsub_topic = google_pubsub_topic.send_mail.id
retry_policy = "RETRY_POLICY_RETRY"
}
build_config {
runtime = "go122"
entry_point = "SendMail"
source {
storage_source {
bucket = google_storage_bucket.function_source.name
object = google_storage_bucket_object.send_mail.name
}
}
}
service_config {
max_instance_count = 1
available_memory = "256M"
timeout_seconds = 60
service_account_email = google_service_account.send_mail.email
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment