Search code examples
google-cloud-platformterraformgoogle-cloud-storageterraform-provider-gcp

How to write Terraform module to create multiple folders in same google cloud storage bucket?


There is a need to create multiple folders in side the Google cloud storage bucket. I am aware that the bucket can be created but not sure how to create multiple folders in the same bucket.

I think below code for one folder in the bucket.

resource "google_storage_bucket" "storage_bucket" {
  name          = "my-test-bucket"
  location      = "us-east4"

  project       = "my-project"
}

resource "google_storage_bucket_object" "my_folder" {
  name          = "fold/"
  bucket        = "${google_storage_bucket.storage_bucket.name}"
}

Can anyone please let me how to do it for multiple folders?


Solution

  • Updated to add content from raj S' answer.


    You could use a set of strings and for_each. Something like below:

    variable "folders" {
      type    = set(string)
      default = []
    }
    
    resource "google_storage_bucket" "storage_bucket" {
      name     = "my-test-bucket"
      location = "us-east4"
      project  = "my-project"
    }
    
    
    resource "google_storage_bucket_object" "folder" {
      for_each = var.folders
    
      name    = each.key
      bucket  = google_storage_bucket.storage_bucket.name
      content = "folder_content"
    }
    

    Then an example input:

    folders = [
      "fold/",
      "dir/",
      ...
    ]
    

    That would dynamically create the fold and dir folders in the bucket from the input.

    If you don't need to make the list of folders dynamic (i.e. hardcode them instead of variable inputs), you can also use locals instead of variables. Something like:

    locals {
      folders = toset([
        "fold/",
        "dir/",
        ...
      ])
    }
    
    resource "google_storage_bucket" "storage_bucket" {
      name     = "my-test-bucket"
      location = "us-east4"
      project  = "my-project"
    }
    
    
    resource "google_storage_bucket_object" "folder" {
      for_each = local.folders
    
      name    = each.key
      bucket  = google_storage_bucket.storage_bucket.name
      content = "folder_content"
    }