Terraform 0.12(尚未发布)还将带来对 HCL2 的支持,它允许您使用可空参数,如下所示:
resource "aws_ebs_volume" "my_volume" {
availability_zone = "xyz"
size = 30
snapshot_id = var.staging_mode ? local.a_specific_snapshot_id : null
}
此 0.12 预览指南中介绍了可为空的参数。
对于 0.12 之前的 Terraform 版本,Markus的答案可能是您最好的选择,尽管我会更明确地使用count
以下内容:
resource "aws_ebs_volume" "staging_volume" {
count = "${var.staging_mode ? 1 : 0}"
availability_zone = "xyz"
size = 30
snapshot_id = "a_specific_snapshot_id"
}
resource "aws_ebs_volume" "non_staging_volume" {
count = "${var.staging_mode ? 0 : 1}"
availability_zone = "xyz"
size = 30
}
请注意,资源名称必须是唯一的,否则 Terraform 会报错。如果您需要引用 EBS 卷,例如aws_volume_attachment
在0.12 之前的版本中,这会导致问题,三元表达式不是惰性的,所以这样的事情不起作用:
resource "aws_volume_attachment" "ebs_att" {
device_name = "/dev/sdh"
volume_id = "${var.staging_mode ? aws_ebs_volume.staging_volume.id : aws_ebs_volume.non_staging_volume.id}"
instance_id = "${aws_instance.web.id}"
}
因为它将尝试评估三元的两侧,其中任何时候只有一个有效。在 Terraform 0.12 中,情况将不再如此,但显然您可以使用可为空的参数更轻松地解决它。