gcp bucket with terraform

Given that this is my first time creating terraform for gcp, surprisingly found it to be similiar to terraform for azure. Here is the simple code to create a bucket and it runs way faster compare to Azure. 

main.tf




terraform {
  required_version = ">= 1.5.0"

  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 6.0"
    }
  }
}

variable "project_id" {
  description = "GCP project ID"
  type        = string
}

variable "bucket_name" {
  description = "Globally unique bucket name"
  type        = string
}

variable "location" {
  description = "Bucket location (australia-southeast1 = Sydney, australia-southeast2 = Melbourne)"
  type        = string
  default     = "australia-southeast1"
}

provider "google" {
  project = var.project_id
}

resource "google_storage_bucket" "this" {
  name     = var.bucket_name
  location = var.location

  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"
  force_destroy               = true # lets terraform destroy delete a non-empty bucket; remove for real data

  versioning {
    enabled = true
  }

  labels = {
    managed-by = "terraform"
  }
}

output "bucket_url" {
  value = google_storage_bucket.this.url
}

terraform.tfvars. 


project_id  = "project-xxxxx"
bucket_name = "mytestbucket-123456789"

And we can easily track our resource creations by going to here :-

Query this from logging explorer :-

protoPayload.methodName="storage.buckets.create"

protoPayload.resourceName="projects/_/buckets/mytestbucket-123456789"




And if you're thinking of setting up a service account to do this 

Using a service account 

gcloud iam service-accounts create terraform-sa --display-name "Terraform"

Providing it with proper permission 

gcloud projects add-iam-policy-binding project-xxx --member="serviceAccount:terraform-sa@project-xxx.iam.gserviceaccount.com" --role="roles/storage.admin"

And then update your terraform code 


provider "google" {
  project = var.project_id
  impersonate_service_account = "terraform-sa@project-xxx.iam.gserviceaccount.com"
}







Comments

Popular posts from this blog

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

llama cpp running it in google colab