0
0
GCPcloud~30 mins

Modules for reusability in GCP - Mini Project: Build & Apply

Choose your learning style9 modes available
Modules for reusability
📖 Scenario: You are working on a Google Cloud Platform project where you need to create reusable infrastructure components. Using Terraform modules helps you avoid repeating code and makes your infrastructure easier to manage.
🎯 Goal: Build a simple Terraform module for creating a Google Cloud Storage bucket, then use that module in your main Terraform configuration to create a bucket with specific settings.
📋 What You'll Learn
Create a Terraform module with a variable for the bucket name
Use the module in the main Terraform configuration
Pass the bucket name to the module
Configure the bucket with versioning enabled
💡 Why This Matters
🌍 Real World
Terraform modules help cloud engineers reuse infrastructure code across projects, saving time and reducing errors.
💼 Career
Knowing how to create and use Terraform modules is a key skill for cloud infrastructure roles, enabling scalable and maintainable deployments.
Progress0 / 4 steps
1
Create the Terraform module folder and main.tf
Create a folder called gcs_bucket_module and inside it create a file main.tf with a resource google_storage_bucket named bucket. Set the bucket name to the variable bucket_name. Do not enable versioning yet.
GCP
Need a hint?

Use resource "google_storage_bucket" "bucket" {} and inside set name = var.bucket_name.

2
Add a variable for the bucket name in the module
Inside the gcs_bucket_module folder, create a file variables.tf and define a variable called bucket_name of type string with no default value.
GCP
Need a hint?

Use variable "bucket_name" { type = string } to declare the variable.

3
Use the module in the main Terraform configuration
In your main Terraform configuration file main.tf (outside the module folder), add a module block named my_bucket that uses the source ./gcs_bucket_module. Pass the bucket name my-unique-bucket-123 to the module variable bucket_name.
GCP
Need a hint?

Use module "my_bucket" { source = "./gcs_bucket_module" bucket_name = "my-unique-bucket-123" }.

4
Enable versioning in the module's storage bucket resource
Modify the google_storage_bucket resource in gcs_bucket_module/main.tf to enable versioning by adding the block versioning { enabled = true } inside the resource.
GCP
Need a hint?

Add versioning { enabled = true } inside the google_storage_bucket resource.