Use block variables

Hi @JulienBreux,

If you will always have exactly one website block then you can just write it out directly with individual references to your object:

resource "google_storage_bucket" "default" {
  website {
    main_page_suffix = var.bucket_website.main_page_suffix
    not_found_page   = var.bucket_website.not_found_page
  }
}

A dynamic block would only be necessary here if the decision about whether or not to include the website block must be made dynamically. For example, you might allow var.bucket_website to be null in order to disable the website functionality altogether:

variable "bucket_website" {
  description = "Bucket website configuration"
  type = object({
    main_page_suffix = string
    not_found_page   = string
  })
  default = null
}

resource "google_storage_bucket" "default" {
  dynamic "website" {
    for_each = var.bucket_website[*]
    content {
      main_page_suffix = website.value.main_page_suffix
      not_found_page   = website.value.not_found_page
    }
  }
}

The var.bucket_website[*] syntax is a special mode of the splat operator [*] when applied to a non-list value: if var.bucket_website is null then it will produce an empty list, and otherwise it will produce a single-element list containing the value. We can use that to concisely adapt a variable that is either null or not into what the dynamic block expects: a list with zero or more elements.

1 Like