I'm trying to deploy a google cloud function using terraform. The function requires the function to be zipped. I need a hello world project with terraform and nodejs. I've been trying for the past few days to set it up, but without a success.
1 Answer
Sample Terraform
resource "google_cloudfunctions_function" "test" {
name = "[FunctionName]"
entry_point = "helloGET"
available_memory_mb = 128
timeout = 61
project = "[GCPProjectName]"
region = "us-central1"
trigger_http = true
trigger_topic = "[PubSubTopic]"
trigger_bucket = "[StorageBucketName]"
source_archive_bucket = "${google_storage_bucket.bucket.name}"
source_archive_object = "${google_storage_bucket_object.archive.name}"
labels {
deployment_name = "test"
}
}
resource "google_storage_bucket" "bucket" {
name = "cloudfunction-deploy-test1"
}
data "archive_file" "http_trigger" {
type = "zip"
output_path = "${path.module}/files/http_trigger.zip"
source {
content = "${file("${path.module}/files/http_trigger.js")}"
filename = "index.js"
}
}
resource "google_storage_bucket_object" "archive" {
name = "http_trigger.zip"
bucket = "${google_storage_bucket.bucket.name}"
source = "${path.module}/files/http_trigger.zip"
depends_on = ["data.archive_file.http_trigger"]
}
Sample nodejs
/**
* HTTP Cloud Function.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.helloGET = function helloGET (req, res) {
res.send(`Hello ${req.body.name || 'World'}!`);
};
4 Comments
aphex
Hi, thank you for the answer. How do you zip the bundle? Just building and then zipping it?
StephenG
@aphex if the nodejs source file is in the right relative path (see the
source in the archive_file data block), terraform will zip for you!CpILL
yeah, but what is the file called and how do you reference it in the terraform template???
StephenG
in the same directory as the module is defined, the template is looking for
files/http_trigger.js (see the content of the archive_file.http_trigger. That file is then renamed to index.js inside of the zip, which is then deployed to a storage bucket