You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform中未声明本地值/变量时如何设置默认磁盘大小?

Solution for Conditional Default Disk Size in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:25:31