Terraform 3 条件

问题描述 投票:0回答:2

是否可以让 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 个变量?

if-statement conditional-statements terraform
2个回答
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]
  }
}

0
投票

我已经在

map
文件中拥有顶级
tfvars
,因此对于 3 个条件,我将它们链接在一起:

vnet_map = {
   id = (var.myapp.environment == "prod")? var.id_prod : (var.myapp.environment == "nonprod")? var.id_nonprod : var.id_dev
}
  • 如果条件超过 3 个,我可能会使用 其他答案以提高可读性
© www.soinside.com 2019 - 2024. All rights reserved.