Terraform IAC: Google Cloud Build

Varunkumar Inbaraj
2 min readJun 11, 2022

GCP Terraform Series 3

I assume you had an initial Terraform and GCP setup. There are multiple ways to automate builds using build triggers. Here I will share the industry standard and sophisticated triggers across the industry if the use GitHub.

Manual Execution Trigger

Here is the code for cloudbuild.tf

resource "google_cloudbuild_trigger" "<internal-any-name>" {
project = var.project_id
name = "<trigger-name>"
description = "<purpose of this trigger>"
source_to_build {
uri = "https://github.com/<company-name>/<repo-name>"
ref = "refs/heads/master"
repo_type = "GITHUB"
}
git_file_source {
path = "path/to/cloudbuild.yaml"
uri = "https://github.com/<company-name>/<repo-name>"
revision = "refs/heads/master"
repo_type = "GITHUB"
}
}

source_to_build - The repo and ref of the repository from which to build. Triggers that respond to such events build source at whatever commit caused the event. This field is currently only used by Webhook, Pub/Sub, Manual, and Cron triggers. One of trigger_template, github, pubsub_config webhook_config or source_to_build must be provided.

git_file_source - The file source describing the local or remote Build template.

GitHub Tag Execution Trigger

Here is the code for cloudbuild.tf

resource "google_cloudbuild_trigger" "<internal-any-name>" {
project = var.project_id
name = "<trigger-name>"
description = "<purpose of this trigger>"
git_file_source {
path = "path/to/cloudbuild.yaml"
uri = "https://github.com/<company-name>/<repo-name>"
revision = format("refs/tags/<prefix>-%s.[v*]",var.env)
repo_type = "GITHUB"
}
github {
owner = "<your-company-name>"
name = <repo-name>
push {
tag = format("refs/tags/<prefix>-%s.[v*]",var.env)
}
}
substitutions = {
_BACKEND_BUCKET = format( "bucket=tf-state-%s",var.project_id)
_BACKEND_CONFIG_PREFIX = "prefix=terraform/<dir-for-stateFile>"
_VAR_FILE = format("generator-%s.tfvars",var.env)
_DIR = "<path/to/dir>"
_TF_DIR = "terraform"
_TF_OPTIONS = "-auto-approve"
_VAR_FILE = format("<if-prefix>-%s.tfvars", var.env)
_TF_COMMAND = "plan"
}
}

github -Describes the configuration of a trigger that creates a build whenever a GitHub event is received. One of trigger_template, github, pubsub_config, or webhook_config must be provided. (In the above example, event is GitHub tag)

substitutions - Substitutions data for Build resource.

--

--