我正在使用Azure DevOps和Terraform在我的订阅中部署多个环境,我正在为我的所有环境(总共3个环境)利用相同的main.tf、variables.tf和tfvar。在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三个选项吗?
发布于 2021-01-27 07:26:12
我认为最简单和最具伸缩性的方法(如果你想稍后添加新的env )就是为它使用一个变量。
如下所示(仅限示例):
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"]中使用不同的密钥为不同的环境创建子网即可。
https://stackoverflow.com/questions/65909285
复制相似问题