LoginSignup
18
7

More than 3 years have passed since last update.

Terraformを使ってCloudFunctionsのzip化とdeployを行う方法

Last updated at Posted at 2020-09-07

CloudFunctionsをTerraform化する際にハマったのでメモ

ハマったポイント

  • deployする時のzip化をどうするか
  • どうやって、ソースの更新があった時のみdeployされるようにするか

TerraformでCloudFunctionsをdeployする時に同じ名前のzipファイルだとdeployされないというissueが上がっている

解消方法

  • zip化
    terraformのarchive_fileを使うとzip化をterraformで出来る

  • ソース更新の取得
    ソース更新があった際にだけzipファイル名を変えればdeploy出来るので、zipファイル名にmd5をつけることで対応

サンプルコード

以下の用なterraformのコードで対応出来た

# archive_fileを使うことでterraform plan時にzipファイルがローカルに作成される
data "archive_file" "function_archive" {
  type        = "zip"
  source_dir  = "path/to/src_dir" # main.pyやrequirement.txtが入ってるdir
  output_path = "path/to/output/functions.zip" # zipファイルの出力パス
}

# zipファイルをアップロードするためのbucket
resource "google_storage_bucket" "bucket" {
  name          = "my-bucket"
  location      = "US"
  storage_class = "STANDARD"
}

# google_storage_bucket_objectを使うことで、ローカルのzipファイルがGCSへアップロードされる
resource "google_storage_bucket_object" "packages" {
  name   = "packages/functions.${data.archive_file.function_archive.output_md5}.zip"
  bucket = google_storage_bucket.bucket.name
  source = data.archive_file.function_archive.output_path
}

resource "google_cloudfunctions_function" "function" {
  name                  = "my-function"
  description           = "terraform deploy test"
  runtime               = "python37"
  source_archive_bucket = google_storage_bucket.bucket.name
  source_archive_object = google_storage_bucket_object.packages.name
  trigger_http          = true
  available_memory_mb   = 128
  timeout               = 120
  entry_point           = "helloGET"
}

これで、ソースの更新があった時だけ、自動でzip化されてdeployされる

18
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
7