Terraform

Deploy GC Functions via Terraform

Hello. In this tutorial, we will deploy a cloud function using terraform script on the google cloud platform.

1. Introduction

Terraform is an open-source tool developed by HashiCorp for building, changing, and versioning the infrastructure safely and efficiently. It is used to manage the infrastructure of the popular cloud service providers and custom in-house solutions. It helps manage both low-level (Compute, Storage, Networking, etc.) and high-level components (such as SaaS, DNS, etc.) Terraform deployment automation is divided into different sections i.e. –

  • IaaC – IaaC is popularly known as the Infrastructure as a Code, describing the infrastructure using a high-level configuration syntax. This allows a blueprint of the infrastructure which can be deployed, versioned, and shared for re-use
  • Execution Plans – Terraform has a planning step where it generates an execution plan. The execution plan tells the administrator what Terraform will do once applied and helps to avoid any surprises when it creates the infrastructure
  • Resource Graph – Terraform builds a graph of all the resources and parallelizes the creation and modification of non-dependent resources. This offers insights into learning the dependencies in their infrastructure
  • Change Automation – Terraform allows to apply of complex changesets to the infrastructure with minimal human intervention

1.1 Steps

To create the infrastructure via the Terraform scripts following commands need to be executed in a sequence. However, details and actions may differ between workflows.

  • terraform init – Initializing the new or existing terraform configuration
  • terraform plan – Generate the execution plan from the resources specified in the file
  • terraform apply – Create the infrastructure from the resources specified in the file
  • terraform destroy – Destroy the created infrastructure
Fig. 1: Terraform workflow

2. Deploy the google cloud function via terraform script

Google Cloud is a cloud computing platform offered by Google. It provides various services like compute engine, storage, networking, big data, and many others that run on google infrastructure. Google cloud function is –

  • Serverless
  • Fully managed
  • Useful in building small microservices
  • Auto scale as the traffic increases
  • Supports event-based triggers. E.g. Http, File upload, Message pushed to pub/sub

2.1 Pre-requisites

To start with you will need –

  • Terraform CLI and the instructions can be read from this link
  • Free tier google cloud account
  • Google Cloud SDK and the instructions can be read from this link

2.2 Creating the nodejs application

To play with the cloud function we need to first create a small nodejs application. Create a file named – index.js in the src folder.

index.js

exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || "Hello World!";
  return res.status(200).json({ status: "up", info: message });
};

2.3 Creating the terraform script

Create the terraform scripts in the terraformcode folder.

2.3.1 Creating the variables script

Create a variables file responsible to declare the global variables.

variables.tf

variable "project_id" {
  type = string
  # replace GCP_PROJECT_ID with your project
  default = "GCP_PROJECT_ID"
}

variable "location" {
  type    = string
  default = "us-central1"
}

variable "bucket_location" {
  type    = string
  default = "US"
}

2.3.2 Creating the main script

We will be using a single terraform script named – main.tf to specify the –

  • Terraform provider
  • Google cloud provider details
  • Resources creation and its IAM binding

main.tf

terraform {
  required_version = ">=0.14"
  backend "local" {}

  required_providers {
    google = ">= 3.3"
  }
}

provider "google" {
  project = var.project_id
  region  = var.location
}

locals {
  timestamp = formatdate("YYMMDDhhmmss", timestamp())
}

# compress source code
data "archive_file" "source" {
  type        = "zip"
  source_dir  = "${path.root}/../src"
  output_path = "${path.root}/../generated/src-${local.timestamp}.zip"
}

# storage bucket that will host the source code
resource "google_storage_bucket" "bucket" {
  name = "tf-cf-bucket-${local.timestamp}"

  location = var.bucket_location
}

# add source code to storage bucket
resource "google_storage_bucket_object" "archive" {
  depends_on = [
    google_storage_bucket.bucket,
    data.archive_file.source
  ]

  name   = "${data.archive_file.source.output_md5}.zip"
  bucket = google_storage_bucket.bucket.name

  source       = data.archive_file.source.output_path
  content_type = "application/zip"
}

# create generation1 cloudfunction
resource "google_cloudfunctions_function" "function" {
  depends_on = [
    google_storage_bucket.bucket,
    google_storage_bucket_object.archive
  ]

  name        = "tf-nodejs-cf-${local.timestamp}"
  description = "learning cf through terraform"
  runtime     = "nodejs16"

  project = var.project_id
  region  = var.location

  available_memory_mb   = 128
  source_archive_bucket = google_storage_bucket.bucket.name
  source_archive_object = google_storage_bucket_object.archive.name
  trigger_http          = true
  timeout               = 60

  # name of the function that will be executed by nodejs
  entry_point = "helloWorld"
  labels = {
    purpose = "learning"
  }

  max_instances = 1
  min_instances = 1
}

# iam entry for all users
resource "google_cloudfunctions_function_iam_member" "invoker" {
  depends_on = [
    google_cloudfunctions_function.function
  ]

  project        = google_cloudfunctions_function.function.project
  region         = var.location
  cloud_function = google_cloudfunctions_function.function.name

  role   = "roles/cloudfunctions.invoker"
  member = "allUsers"
}

3. Code run and demo

Navigate to the project’s terraformcode directory containing the terraform scripts and open the terminal. Execute the below commands in the respective order within the directory.

Commands

-- step1: initializing the new or existing terraform configuration --
terraform init


-- step2: generating the execution plan --
terraform plan


-- step3: building the infrastructure --
-- auto-approve flag skips interactive approval of the plan before applying
terraform apply --auto-approve


-- step4: destroying the infrastructure --
-- auto-approve flag skips interactive approval of the plan before applying
terraform destroy --auto-approve

Once the script is executed successfully head over to the google cloud function to confirm whether the resource is created successfully or not. If everything goes well the resource will be created as shown below.

Fig. 2: Created resource

You can copy the cloud function endpoint from the trigger tab of the created cloud function. Open the browser of your choice and hit the endpoint. The hello app response will be shown.

Fig. 3: Application response

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned an introduction to Terraform and deployed a simple cloud function via terraform script. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial to deploy a cloud function via terraform script.

Download
You can download the full source code of this example here: Deploy the google cloud function via terraform script

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button