My First Terraform Module
Terraform module to create Pub/Sub notifications for Google Cloud Storage.
Introduction
I have been working on Terraform for last one year. In couple of projects we had a requirement to “establish a flow of event notification from Google Cloud Storage to a Cloud Pub/Sub.”
As part of creating this flow, we need to:
- Create a Google Cloud Storage bucket
- Create a Cloud Pub/Sub topic
- In order to enable notification, a special cloud storage service account unique to each project must have the IAM permission “roles/pubsub.publisher”.
- Create notification configured for a bucket for multiple trigger events.
Same code we had to copy and paste in several places with change in bucket_name, topic_name and trigger_event.
With Terraform, you can put your code inside of a Terraform module and reuse that module in multiple places throughout your code. Instead of having the same code copy/pasted in the staging and production environments, you’ll be able to have both environments reuse code from the same module.
Benefits of Modules
- Organize configuration
- Encapsulate configuration
- Re-use configuration
- Provide consistency
- Ensure best practices
My Module: terraform-google-storage-pubsub
https://registry.terraform.io/modules/vikramshinde12/storage-pubsub/google/latest
This module creates following resources:
- Bucket : A Source bucket
- Topic : The topic in Pub/Sub that receives notifications.
- Event : The events that trigger a notification to be sent. e.g. OBJECT_FINALIZE (default) — New object is successfully created in the bucket. OBJECT_DELETE — an object has been successfully deleted.
- Subscriber: Sample pull subscriber named “echo”.
Input Variables
- bucket_name: Source bucket name on which Pub/Sub notification is configured.
- topic_name: The topic in Pub/Sub that receives notifications.
- event_type (optional): Trigger event type e.g. OBJECT_FINALIZE, OBJECT_DELETE, OBJECT_ARCHIVE.
- project_id: Project Id
Output Variables
- bucket_url: The Bucket Link URL
- topic_name: The URI of the Pub/Sub Topic.
Example usage
Following is the simple code how to call the module in Terraform configurations.
resource "google_project_service" "pubsub_api" {
project = "sample_project_id"
service = "pubsub.googleapis.com"
}module "gcs-pubsub" {
source = "vikramshinde12/storage-pubsub/google"
version = 1.0.1
topic_name = "sample_topic"
bucket_name = "sample_bucket"
project_id = "sample_project_id"
depends_on = [google_project_service.pubsub_api]
}
Conclusion
This way I created a simple Terraform module in a the Terraform Registry as per minimal recommendation from Terraform. The Terraform Registry is integrated directly into Terraform to make it easy to use providers and modules.
Reference
👋 Join FAUN today and receive similar stories each week in your inbox! ️ Get your weekly dose of the must-read tech stories, news, and tutorials.
Follow us on Twitter 🐦 and Facebook 👥 and Instagram 📷 and join our Facebook and Linkedin Groups 💬