[A-00134]TerraformでCloudFunctionsを作成する

Terraformを使ってGoogleCloudのCloudFunctionsを作成したいと思います。

本記事ではgcloudコマンドを使用します。下記の記事でgcloudを使えるようにしておいてください。

・イメージ図

今回作成する構成図はこんな感じです。CloudShellからFunctionsを呼び出すだけです。

・APIを有効化する

gcloud services enable artifactregistry.googleapis.com \
  cloudbuild.googleapis.com \
  cloudfunctions.googleapis.com \
  logging.googleapis.com \
  pubsub.googleapis.com \
  run.googleapis.com

・Terraformを作成する

まずはtest用ディレクトリを作成します。

mkdir test-functions
cd test-functions
touch main.tf

・ソースを取得する

下記コマンドより、functionsにエントリーするソースを取得し、zipする。

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

次に所定のディレクト配下にあるソースをzipする

cd nodejs-docs-samples/functions/helloworld/helloworldHttp
zip -r function-source.zip .

上記で資材準備は完了

・Terraformを実行する

次にmain.tfを作成します。コードは下記のようになります。

terraform {
  required_providers {
    google = {
        source = "hashicorp/google"
        version = ">= 4.34.0"
    }
  }
}

resource "random_id" "default" {
  byte_length = 8
}

resource "google_storage_bucket" "default" {
  name = "${random_id.default.hex}-gcf-sorce"
  location = "ASIA"
  uniform_bucket_level_access = true
}

data "archive_file" "default" {
    type = "zip"
    output_path = "/tmp/function-source.zip"
    source_dir = "nodejs-docs-samples/functions/helloworld/helloworldHttp"
}

resource "google_storage_bucket_object" "object" {
    name = "function-source.zip"
    bucket = google_storage_bucket.default.name
    source = data.archive_file.default.output_path
}

resource "google_cloudfunctions2_function" "default" {
    name = "function-v2"
    location = "asia-northeast1"
      description = "a new function"

  build_config {
    runtime     = "nodejs16"
    entry_point = "helloHttp" # Set the entry point
    source {
      storage_source {
        bucket = google_storage_bucket.default.name
        object = google_storage_bucket_object.object.name
      }
    }
  }

  service_config {
    max_instance_count = 1
    available_memory = "256M"
    timeout_seconds = 60
  }
}

output "function_url" {
 value = google_cloudfunctions2_function.default.service_config[0].uri 
}

上記のソースを記載した後、terraformコマンドを実行していく

terraform init
terraform plan
terraform apply

上記を実行すると下記のようなアウトプットが表示される。

function_url = "https://function-v2- xxxxx.a.run.app"

curlでfunctionsにアクセスする

curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" <function_url>
@cloudshell:~/test-functions (xxxx)$ curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://function-v2-xxxxx.a.run.app
Hello World!

上記が確認できたらterraformでdestroyする

terraform destroy

・Appendix

公式ドキュメントはこちら

https://cloud.google.com/functions/docs/tutorials/terraform?hl=ja

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloudfunctions_function.html

参考文献はこちら

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*