Terraform, (AzureRM)是否可以使用if, else, else(条件情况)进行资源部署?



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

Main.tf:

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"]
}

Variables.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变量的环境?也就是说,我可以使用条件格式来选择a, b或c(三个选项)吗?

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

以下内容(仅限示例):

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"]中使用不同的密钥来为不同的环境创建子网。

相关内容

  • 没有找到相关文章

最新更新