azure - 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 三个选项)吗?
解决方案
我认为最简单和最具可扩展性的方法(如果您想稍后添加新环境)是为其使用一个变量。
如下所示(仅示例):
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"]
来为不同的环境创建子网。
推荐阅读
- java - 尝试通过 cmd 运行 java 代码时出现 JNI 错误
- javascript - 如果它不是javascript中的数字,如何将字符串转换为数字并保留字符串?
- javascript - 运行两个函数异步Javascript的问题
- python - Python:我可以制作 2 个或多个具有不同行数的 numpy 数组,具有相同的行数吗?
- javascript - Uncaught TypeError: selectedText.split is not a function ,我的代码有什么问题
- c# - C# Entity Framework 在 ExecuteFunction 上引发错误
- html - 是否值得使用 *{margin:0; padding:0;} 作为重置目的
- c# - 使用导入的架构编译 XmlSchemaSet
- java - 如何进一步优化 Spark 数据集的枢轴
- swift - 从 Firebase 中删除帖子