
This tutorial explains how to manage infrastructure as code with Terraform and Cloud Build using the popular GitOps methodology.
The term GitOps was first coined by Weaveworks, and its key concept is using a Git repository to store the environment state that you want.
Terraform is a HashiCorp open source tool that enables you to predictably create, change, and improve your cloud infrastructure by using code. In this tutorial, you use Cloud Build, a Google Cloud continuous integration service, to automatically apply Terraform manifests to your environment.
This tutorial is for developers and operators who are looking for an elegant strategy to predictably make changes to infrastructure. The article assumes you are familiar with Google Cloud, Linux, and GitHub.
The State of DevOps reports identified capabilities that drive software delivery performance. This tutorial will help you with the following capabilities:
Architecture
To demonstrate how this tutorial applies GitOps practices for managing Terraform executions, consider the following architecture diagram. Note that it uses GitHub branches—dev
and prod
—to represent actual environments. These environments are defined by Virtual Private Cloud (VPC) networks—dev
and prod
, respectively—into a Google Cloud project.
Note: For simplicity, this tutorial implements only dev
and prod
environments using VPCs. You can extend this behavior to deploy to more environments and to create projects under your organization hierarchy if needed.
The process starts when you push Terraform code to either the dev
or prod
branch. In this scenario, Cloud Build triggers and then applies Terraform manifests to achieve the state you want in the respective environment. On the other hand, when you push Terraform code to any other branch—for example, to a feature branch—Cloud Build runs to execute terraform plan,
but nothing is applied to any environment.
Ideally, either developers or operators must make infrastructure proposals to non-protected branches and then submit them through pull requests. The Cloud Build GitHub app, discussed later in this tutorial, automatically triggers the build jobs and links the terraform plan
reports to these pull requests. This way, you can discuss and review the potential changes with collaborators and add follow-up commits before changes are merged into the base branch.
If no concerns are raised, you must first merge the changes to the dev
branch. This merge triggers an infrastructure deployment to the dev
environment, allowing you to test this environment. After you have tested and are confident about what was deployed, you must merge the dev
branch into the prod
branch to trigger the infrastructure installation to the production environment.
Objectives
- Set up your GitHub repository.
- Configure Terraform to store state in a Cloud Storage bucket.
- Grant permissions to your Cloud Build service account.
- Connect Cloud Build to your GitHub repository.
- Change your environment configuration in a feature branch.
- Promote changes to the development environment.
- Promote changes to the production environment.
Before you begin
- In the Google Cloud Console, on the project selector page, select or create a Google Cloud project. Note: If you don’t plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Go to project selector
- Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.
- In the Cloud Console, activate Cloud Shell.Activate Cloud ShellAt the bottom of the Cloud Console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Cloud SDK already installed, including the
gcloud
command-line tool, and with values already set for your current project. It can take a few seconds for the session to initialize. - In Cloud Shell, get the ID of the project you just selected:
gcloud config get-value project

- If this command doesn’t return the project ID, configure Cloud Shell to use your project. Replace
PROJECT_ID
with your project ID.
gcloud config set project PROJECT_ID
- Enable the required APIs:
gcloud services enable cloudbuild.googleapis.com compute.googleapis.com

- This step might take a few minutes to finish.
- If you’ve never used Git in Cloud Shell, configure it with your name and email address:
git config --global user.email "your-email-address"
git config --global user.name "your-name"

Git uses this information to identify you as the author of the commits that you create in Cloud Shell.
Setting up your GitHub repository
In this tutorial, you use a single Git repository to define your cloud infrastructure. You orchestrate this infrastructure by having different branches corresponding to different environments:
- The
dev
branch contains the latest changes that are applied to the development environment. - The
prod
branch contains the latest changes that are applied to the production environment.
With this infrastructure, you can always reference the repository to know what configuration is expected in each environment and to propose new changes by first merging them into the dev
environment. You then promote the changes by merging the dev
branch into the subsequent prod
branch.
To get started, you fork the solutions-terraform-cloudbuild-gitops repository.
- On GitHub, navigate to https://github.com/GoogleCloudPlatform/solutions-terraform-cloudbuild-gitops.git.
- In the top-right corner of the page, click Fork.

It will ask you for your own github account’s credentials.

- Now you have a copy of the
solutions-terraform-cloudbuild-gitops
repository with source files.

- In Cloud Shell, clone this forked repository, replacing
your-github-username
with your GitHub username:
cd ~
git clone https://github.com/your-github-username/solutions-terraform-cloudbuild-gitops.git
cd ~/solutions-terraform-cloudbuild-gitops

5. The code in this repository is structured as follows:
- The
environments/
folder contains subfolders that represent environments, such asdev
andprod
, which provide logical separation between workloads at different stages of maturity, development and production, respectively. Although it’s a good practice to have these environments as similar as possible, each subfolder has its own Terraform configuration to ensure they can have unique settings as necessary. - The
modules/
folder contains inline Terraform modules. These modules represent logical groupings of related resources and are used to share code across different environments. - The
cloudbuild.yaml
file is a build configuration file that contains instructions for Cloud Build, such as how to perform tasks based on a set of steps. This file specifies a conditional execution depending on the branch Cloud Build is fetching the code from, for example:- For
dev
andprod
branches, the following steps are executed:terraform init
terraform plan
terraform apply
- For any other branch, the following steps are executed:
terraform init
for allenvironments
subfoldersterraform plan
for allenvironments
subfolders
- For
The reason terraform init
and terraform plan
run for all environments
subfolders is to make sure that the changes being proposed hold for every single environment. This way, before merging the pull request, you can review the plans to make sure access is not being granted to an unauthorized entity, for example.


Configuring Terraform to store state in a Cloud Storage bucket
By default, Terraform stores state locally in a file named terraform.tfstate
. This default configuration can make Terraform usage difficult for teams, especially when many users run Terraform at the same time and each machine has its own understanding of the current infrastructure.
To help you avoid such issues, this section configures a remote state that points to a Cloud Storage bucket. Remote state is a feature of backends and, in this tutorial, is configured in the backend.tf
files—for example:
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
terraform {
backend "gcs" {
bucket = "PROJECT_ID-tfstate"
prefix = "env/dev"
}
}
In the following steps, you create a Cloud Storage bucket and change a few files to point to your new bucket and your Google Cloud project.
- In Cloud Shell, create the Cloud Storage bucket:
PROJECT_ID=$(gcloud config get-value project)
gsutil mb gs://${PROJECT_ID}-tfstate


- Enable Object Versioning to keep the history of your deployments:
gsutil versioning set on gs://${PROJECT_ID}-tfstate

Enabling Object Versioning increases storage costs, which you can mitigate by configuring Object Lifecycle Management to delete old state versions.
3. Replace the PROJECT_ID
placeholder with the project ID in both the terraform.tfvars
and backend.tf
files:
cd ~/solutions-terraform-cloudbuild-gitops
sed -i s/PROJECT_ID/$PROJECT_ID/g environments/*/terraform.tfvars
sed -i s/PROJECT_ID/$PROJECT_ID/g environments/*/backend.tf

4. Check whether all files were updated:
git status
The output looks like this:
On branch dev
Your branch is up-to-date with 'origin/dev'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: environments/dev/backend.tf
modified: environments/dev/terraform.tfvars
modified: environments/prod/backend.tf
modified: environments/prod/terraform.tfvars
no changes added to commit (use "git add" and/or "git commit -a")

5. Commit and push your changes:
git add --all
git commit -m "Update project IDs and buckets"
git remote set-url origin https://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@github.com/rajeevkghosh/solutions-terraform-cloudbuild-gitops
git pull https://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@github.com/rajeevkghosh/solutions-terraform-cloudbuild-gitops.git
git push origin dev
Note: Here, “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” is github access token. To know more about access tokens , read my previous article: “Google Cloud: Configuring CL/CD Pipeline Using Cloud Build And GitHub”




Depending on your GitHub configuration, you will have to authenticate to push the preceding changes.
Granting permissions to your Cloud Build service account
To allow Cloud Build service account to run Terraform scripts with the goal of managing Google Cloud resources, you need to grant it appropriate access to your project. For simplicity, project editor access is granted in this tutorial. But when the project editor role has a wide-range permission, in production environments you must follow your company’s IT security best practices, usually providing least-privileged access.
- In Cloud Shell, retrieve the email for your project’s Cloud Build service account:
CLOUDBUILD_SA="$(gcloud projects describe $PROJECT_ID \
--format 'value(projectNumber)')@cloudbuild.gserviceaccount.com"

Note: This Service account is created when you enable the Cloud Build services.
- Grant the required access to your Cloud Build service account:
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member serviceAccount:$CLOUDBUILD_SA --role roles/editor

Directly connecting Cloud Build to your GitHub repository
This section shows you how to install the Cloud Build GitHub app. This installation allows you to connect your GitHub repository with your Google Cloud project so that Cloud Build can automatically apply your Terraform manifests each time you create a new branch or push code to GitHub.
The following steps provide instructions for installing the app only for the solutions-terraform-cloudbuild-gitops
repository, but you can choose to install the app for more or all your repositories.
- Go to the GitHub Marketplace page for the Cloud Build app:Open the Cloud Build app page
- If this is your first time configuring an app in GitHub: Click Setup with Google Cloud Build at the bottom of the page. Then click Grant this app access to your GitHub account.
- If this is not the first time configuring an app in GitHub: Click Configure access. The Applications page of your personal account opens.

- Click Configure in the Cloud Build row.

- Select Only select repositories, then select
solutions-terraform-cloudbuild-gitops
to connect to the repository.

- Click Save or Install—the button label changes depending on your workflow. You are redirected to Google Cloud to continue the installation.
- Sign in with your Google Cloud account. If requested, authorize Cloud Build integration with GitHub.

- On the Cloud Build page, select your project. A wizard appears.

- In the Select repository section, select your GitHub account and the
solutions-terraform-cloudbuild-gitops
repository.
Select Source as : GitHub(Cloud Build GitHub App) and Click Continue.

8. Put the required details below like “GitHub Account Name” and “Repository”.
If you agree with the terms and conditions, select the checkbox, then click Connect.


- In the Create a trigger section, click Create a trigger and add the trigger name.
- In the Event section, select Push to a branch, enter
.*
in the Base Branch field, and then click Create.


The Cloud Build GitHub app is now configured, and your GitHub repository is linked to your Google Cloud project. From now on, changes to the GitHub repository trigger Cloud Build executions, which report the results back to GitHub by using GitHub Checks.
Changing your environment configuration in a new feature branch
By now, you have most of your environment configured. So it’s time to make some code changes in your development environment.
- On GitHub, navigate to the main page of your forked repository.
- Make sure you are in the
dev
branch. - To open the file for editing, go to the
modules/firewall/main.tf
file and click the pencil icon.


- On line 30, fix the
"http-server2"
typo intarget_tags
field.The value must be"http-server"
.

- Add a commit message at the bottom of the page, such as “Fixing http firewall target”, and select Create a new branch for this commit and start a pull request.

- Click Propose changes.
- On the following page, click Create pull request to open a new pull request with your change.Once your pull request is open, a Cloud Build job is automatically initiated.

- Click Show all checks and wait for the check to become green.

- Click Details to see more information, including the output of the
terraform plan
at View more details on Google Cloud Build link.

You will see something like below:

Note that the Cloud Build job ran the pipeline defined in the cloudbuild.yaml
file. As discussed previously, this pipeline has different behaviors depending on the branch being fetched.
9. The build checks whether the $BRANCH_NAME
variable matches any environment folder. If so, Cloud Build executes terraform plan
for that environment. Otherwise, Cloud Build executes terraform plan
for all environments to make sure that the proposed change holds for them all. If any of these plans fail to execute, the build fails as well.
Build History:

- id: 'tf plan'
name: 'hashicorp/terraform:1.0.0'
entrypoint: 'sh'
args:
- '-c'
- |
if [ -d "environments/$BRANCH_NAME/" ]; then
cd environments/$BRANCH_NAME
terraform plan
else
for dir in environments/*/
do
cd ${dir}
env=${dir%*/}
env=${env#*/}
echo ""
echo "*************** TERRAFOM PLAN ******************"
echo "******* At environment: ${env} ********"
echo "*************************************************"
terraform plan || exit 1
cd ../../
done
fi
10. Similarly, the terraform apply
command runs for environment branches, but it is completely ignored in any other case. In this section, you have submitted a code change to a new branch, so no infrastructure deployments were applied to your Google Cloud project.
- id: 'tf apply'
name: 'hashicorp/terraform:1.0.0'
entrypoint: 'sh'
args:
- '-c'
- |
if [ -d "environments/$BRANCH_NAME/" ]; then
cd environments/$BRANCH_NAME
terraform apply -auto-approve
else
echo "***************************** SKIPPING APPLYING *******************************"
echo "Branch '$BRANCH_NAME' does not represent an oficial environment."
echo "*******************************************************************************"
fi
Enforcing Cloud Build execution success before merging branches
To make sure merges can be applied only when respective Cloud Build executions are successful, proceed with the following steps:
- On GitHub, navigate to the main page of your forked repository.

- Under your repository name, click Settings.
- In the left menu, click Branches.

- Under Branch protection rules, click Add rule.
- In Branch name pattern, type
dev
. - In the Protect matching branches section, select Require status checks to pass before merging.
- Search for your Cloud Build trigger name created previously, and click Save changes.

- Click Create. Then Click Save Changes.

- Repeat steps 4–8, setting Branch name pattern to
prod
.

After you click on Create and Then Save Changes, you will have something like below:

This configuration is important to protect both the dev
and prod
branches. Meaning, commits must first be pushed to another branch, and only then they can be merged to the protected branch. In this tutorial, the protection requires that the Cloud Build execution be successful for the merge to be allowed.
Promoting changes to the development environment
You have a pull request waiting to be merged. It’s time to apply the state you want to your dev
environment.
- On GitHub, navigate to the main page of your forked repository.
- Under your repository name, click Pull requests.

- Click the pull request you just created. Here in our case click on “Update main.tf”.

- Click Merge pull request, and then click Confirm merge.

You will see something like below:

- Check that a new Cloud Build has been triggered:Go to the Cloud Build page

- Open the build and check the logs.When the build finishes, you see something like this:
Step #3 - "tf apply": external_ip = external-ip-value
Step #3 - "tf apply": firewall_rule = dev-allow-http
Step #3 - "tf apply": instance_name = dev-apache2-instance
Step #3 - "tf apply": network = dev
Step #3 - "tf apply": subnet = dev-subnet-01

- Copy
external-ip-value
( In our case, its “34.127.112.60” ) and open the address in a web browser.This provisioning might take a few seconds to boot the VM and to propagate the firewall rule, but at the end, you see Environment: dev in the web browser.

Promoting changes to the production environment
Now that you have your development environment fully tested, you can promote your infrastructure code to production.
- On GitHub, navigate to the main page of your forked repository.

- Under your repository name, click Pull requests. then Click on New pull request.

- For the base repository, select your just-forked repository.
- For base, select
prod
from your own base repository. For compare, selectdev
. Click “Create pull request”. This will open a new window and ask you for “Title”.

- For title, enter a title such as
Promoting networking changes
, and then click Create pull request.


- Review the proposed changes, including the
terraform plan
details from Cloud Build, and then click Merge pull request.

- Click Confirm merge.

- In the Cloud Console, open the Build History page to see your changes being applied to the production environment:Go to the Cloud Build page

- Wait for the build to finish, and then check the logs.At the end of the logs, you see something like this:
Step #3 - "tf apply": external_ip = external-ip-value
Step #3 - "tf apply": firewall_rule = prod-allow-http
Step #3 - "tf apply": instance_name = prod-apache2-instance
Step #3 - "tf apply": network = prod
Step #3 - "tf apply": subnet = prod-subnet-01


- Copy
external-ip-value
and open the address in a web browser.This provisioning might take a few seconds to boot the VM and to propagate the firewall rule, but in the end, you see Environment: prod in the web browser.

You have successfully configured a serverless infrastructure-as-code pipeline on Cloud Build. In the future, you might want to try the following:
- Add deployments for separate use cases.
- Create additional environments to reflect your needs.
- Use a project per environment instead of a VPC per environment.
Clean up
After you’ve finished the tutorial, clean up the resources you created on Google Cloud so you won’t be billed for them in the future.
Deleting the project
- Everything in the project is deleted. If you used an existing project for this tutorial, when you delete it, you also delete any other work you’ve done in the project.
- Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an
appspot.com
URL, delete selected resources inside the project instead of deleting the whole project. - In the Cloud Console, go to the Manage resources page.Go to Manage resources
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Deleting the GitHub repository
To avoid blocking new pull requests on your GitHub repository, you can delete your branch protection rules:
- In GitHub, navigate to the main page of your forked repository.
- Under your repository name, click Settings.
- In the left menu, click Branches.
- Under the Branch protection rules section, click the Delete button for both
dev
andprod
rows.
Optionally, you can completely uninstall the Cloud Build app from GitHub:
- Go to your GitHub Applications settings.Go to the GitHub applications page
- In the Installed GitHub Apps tab, click Configure in the Cloud Build row. Then, in the Danger zone section, click the Uninstall button in the Uninstall Google Cloud Builder row.At the top of the page, you see a message saying “You’re all set. A job has been queued to uninstall Google Cloud Build.”
- In the Authorized GitHub Apps tab, click the Revoke button in the Google Cloud Build row, then I understand, revoke access in the popup.
If you don’t want to keep your GitHub repository:
- In GitHub, go to the main page of your forked repository.
- Under your repository name, click Settings.
- Scroll down to the Danger Zone.
- Click Delete this repository, and follow the confirmation steps.
That Concludes our tutorial on Managing infrastructure as code with Terraform, Cloud Build, and GitOps
Your article helped me a lot, is there any more related content? Thanks!