Terraform中未声明本地值/变量时如何设置默认磁盘大小?
Unfortunately, there is no way to reference an undeclared local value or variable in Terraform and fall back to a default. Terraform's validation phase checks all references before evaluating any functions—so even can() or try() can't prevent errors when referencing something that hasn't been declared.
The standard and recommended workaround is to explicitly declare the value with a default of null, then use a conditional or coalesce() to handle the fallback:
For Local Values
locals { default_disk_size = null # Explicit declaration with null default } resource "google_compute_disk" "terraform-additional-persistent-disk" { name = "terraform-additional-persistent-disk" zone = local.zone type = local.default_disk_type size = local.default_disk_size != null ? local.default_disk_size : 50 image = local.default_ubuntu_image labels = { created_by = "terraform" } }
For Input Variables
variable "default_disk_size" { type = number default = null } resource "google_compute_disk" "terraform-additional-persistent-disk" { name = "terraform-additional-persistent-disk" zone = local.zone type = local.default_disk_type size = var.default_disk_size != null ? var.default_disk_size : 50 image = local.default_ubuntu_image labels = { created_by = "terraform" } }
Concise Syntax with coalesce()
You can use Terraform's coalesce() function for a shorter expression—it returns the first non-null value in the list:
size = coalesce(local.default_disk_size, 50)
This approach ensures validation passes, and Terraform will use the declared value if it's set (not null), otherwise fall back to the default of 50.
内容的提问来源于stack exchange,提问作者rodvictor

