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

Create multiple GCP storage buckets using terraform


I have used terraform scripts to create resources in GCP. The scripts are working fine. But my question is - how do I create multiple storage buckets using a single script. I have two files for creating the storage bucket- main.tf which has the terraform code to create the buckets . variables.tf which has the actual variables like storage bucket name, project_id, etc, which looks like this:

variable "storage_class" { default = "STANDARD" }
variable "name" { default = "internal-demo-bucket-1"}
variable "location" { default = "asia-southeast1" }

How can I provide more than one bucket name in the variable name? I tried to provide multiple names in an array but the build failed.


Solution

  • I don't know all your requirements, however suppose you need to create a few buckets with different names, while all other bucket characteristics are constant for every bucket in the set under discussion.

    I would create a variable, i.e. bucket_name_set in a variables.tf file:

    variable "bucket_name_set" {
      description = "A set of GCS bucket names..."
      type        = list(string)
    }
    

    Then, in the terraform.tfvars file, I would provide unique names for the buckets:

    bucket_name_set = [
      "some-bucket-name-001",
      "some-bucket-name-002",
      "some-bucket-name-003",
    ]
    

    Now, for example, in the main.tf file I can describe the resources:

    resource "google_storage_bucket" "my_bucket_set" {
      project       = "some project id should be here"
    
      for_each      = toset(var.bucket_name_set)
      name          = each.value     # note: each.key and each.value are the same for a set
    
      location      = "some region should be here"
      storage_class = "STANDARD"
      force_destroy = true
    
      uniform_bucket_level_access = true
    }
    

    Terraform description is here: The for_each Meta-Argument

    Terraform description for the GCS bucket is here: google_storage_bucket

    Terraform description for input variables is here: Input Variables