是否可以让 terraform 在 3 个语句之间做出决定?就像 if、else、else 一样?
我想运行类似于以下内容的东西:
<CONDITION> ? <val_one> : <val_two> : <val_three>
或者换句话说/不同的例子:
var.true_false_other ? var.true_statement : var.false_statement : var.other_statement
这样的事情可能吗?
编辑:添加示例, 主要.tf:
resource "azurerm_subnet" "subnet" {
for_each = var.true_false_other ? var.subnet1 : var.subnet2 : var.subnet3
name = each.value["subnet"]
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.vnet-example.name
address_prefixes = [each.value["address_prefixes"]]
}
变量.tf:
variable "subnet1" {
description = "Subnet 1 variable"
}
variable "subnet2" {
description = "Subnet 2 variable"
}
variable "subnet3" {
description = "Subnet 3 variable"
}
tfvars:
subnet1 = {
subnet1A-reference = {
subnet = "subnet1A"
address_prefixes = "x.x.x.x/24"
},
subnet1B-reference = {
subnet = "subnet1B"
address_prefixes = "x.x.x.y/24"
}
}
subnet2 = {
subnet2A-reference = {
subnet = "subnet2A"
address_prefixes = "x.x.x.x/24"
},
subnet2B-reference = {
subnet = "subnet2B"
address_prefixes = "x.x.x.y/24"
}
}
subnet3 = {
subnet3A-reference = {
subnet = "subnet3A"
address_prefixes = "x.x.x.x/24"
},
subnet3B-reference = {
subnet = "subnet3B"
address_prefixes = "x.x.x.y/24"
}
}
所以本质上,根据我告诉 terraform 的内容,我希望它选择 3 个选项之一,并且只选择 3 个选项中的 1 个。有没有办法告诉它只选择其中 1 个变量?
我想根据 Level_tag 变量定义一个子网名称。这就是我最终得到的结果,而不是条件:
variable "Level_tag" {
type = string
default = "Development
}
locals {
Level_map = {
"Development" = "DevelopmentInstances"
"Staging" = "StagingInstances"
"Production" = "ProductionInstances"
}
}
data "aws_subnet" "subnet" {
vpc_id = data.aws_vpc.vpc.id
tags = {
Name = local.Level_map[var.Level_tag]
}
}
我已经在
map
文件中拥有顶级 tfvars
,因此对于 3 个条件,我将它们链接在一起:
vnet_map = {
id = (var.myapp.environment == "prod")? var.id_prod : (var.myapp.environment == "nonprod")? var.id_nonprod : var.id_dev
}