首页 > 解决方案 > Terraform,(AzureRM)您可以为资源部署提供 if、else、else(条件情况)吗?

问题描述

我正在使用 Azure DevOps 和 Terraform 在我的订阅中部署多个环境,并且我为我的所有环境(总共 3 个环境)使用相同的 main.tf、variables.tf 和 tfvars。在 tf 文件和 tfvars 文件中,我在变量组(特定于 Azure DevOps)中传递 DevOps 变量以识别不同的变量和值。例如,我想用相同的资源(每个订阅 1 个)构建 3 个不同的子网:

主文件:

resource "azurerm_subnet" ""example" { 
  for_each             = var.is_env_one ? var.subnet_range_one : var.subnet_range_two : var.subnet_range_three
  resource_group_name  = azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name

  name                 = each.value["name"]
  address_prefixes     = each.value["address_prefixes"]
}

变量.tf:

variable "is_env_one" {
  description = "Boolean on if this is environment 1 or not"
  default = true 
}
variable "is_env_two" {
  description = "Boolean on if this is environment 2 or not"
  default = true 
}
variable "is_env_three" {
  description = "Boolean on if this is environment 3 or not"
  default = true 
}
variable "subnet_range_one" {
  description = "tfvars file will dictate # of subnets and values"
}
variable "subnet_range_two" {
  description = "tfvars file will dictate # of subnets and values"
}
variable "subnet_range_three" {
  description = "tfvars file will dictate # of subnets and values"
}

tfvars 信息(范围配置 1 的示例):

subnet_range_one = {
  subnet_1 = {
    name             = "{[_subnet-devops-name_]}" #Azure DevOps Variable that dictates the value
    address_prefixes = "{[_subnet-devops-address-prefix_]}" #Azure DevOps Variable that dictates the value
  }
}

有没有办法让我编写代码来区分使用 DevOps 变量的环境?Aka,我可以使用条件格式说选择 a、b 或 c 三个选项)吗?

标签: azureif-statementconditional-statementsterraform

解决方案


我认为最简单和最具可扩展性的方法(如果您想稍后添加新环境)是为其使用一个变量。

如下所示(仅示例):

variable "env_subnets" {

  default = {

      env1 = [
          {
              name = name11
              address_prefixes = prefix11
          },
          {
              name = name12
              address_prefixes = prefix12
          }          
      ],
      env2 = [
          {
              name = name21
              address_prefixes = prefix21
          },
          {
              name = name22
              address_prefixes = prefix22
          }          
      ],
      env3 = [
          {
              name = name31
              address_prefixes = prefix31
          },
          {
              name = name32
              address_prefixes = prefix32
          }          
      ]
  }
}


resource "azurerm_subnet" "example" { 

  for_each             = {for idx, val in var.env_subnets["env1"]: idx => val}

  resource_group_name  = azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name

  name                 = each.value["name"]
  address_prefixes     = each.value["address_prefixes"]
}

在上面,您只需使用不同的密钥var.env_subnets["env1"]来为不同的环境创建子网。


推荐阅读