variables - 在 Terraform 中,我可以选择是否根据不同的变量来寻址变量吗?网卡,动态静态

标签 variables terraform terraform-provider-azure nic

我试图看看 Terraform 代码中是否有一种方法可以根据不同变量的输入选择性地提供对变量的需求。例如,我有一个在 Azure 中创建 NIC 的模块,代码如下所示:

resource "azurerm_network_interface" "networkinterace" {
  name                = "${var.vm_name}-NIC1"
  resource_group_name = azurerm_resource_group.vm_resource_group.name
  location            = azurerm_resource_group.vm_resource_group.location
  ip_configuration { 
    name                          = "IPName"
    subnet_id                     = var.subnet_id
    private_ip_address_allocation = var.ip_address_allocation #You can set this to Static
    private_ip_address            = var.private_ip
    }
  tags                 = var.tags 
}

如果用户决定 private_ip_address_allocation 值为“动态”,则不需要 private_ip_address。但是,如果用户确定该值是“静态”,那么实际上需要该值。

我的直接解决方案是让用户在选择静态时输入 IP 值 x.x.x.x,如果选择动态则输入“null”。然而,一遍又一遍地运行该计划将表明将会发生变化,并且如果运行 apply,IP 将更改为 null。这实际上不会对 NIC 本身执行任何操作,但我希望它更加幂等,并表明如果运行 Plan,则不会进行任何更改。想法?

最佳答案

你可以做到。

我假设某个地方有一个名为 is_dynamic 的变量:

variable "is_dynamic" {
     default = true
}

然后在您的网络接口(interface)中,您可以按如下方式设置您的 private_ip_address:

ip_configuration {
   ...
   private_ip_address = var.is_dynamic ? null : var.private_ip
   ...
   }

或者您可能将“动态”和“静态”作为变量值:

variable "allocation" {
    default = "Dynamic"
}

那么你可以尝试类似的事情

ip_configuration {
   ...
   private_ip_address = var.allocation == "Dynamic" ? null : var.private_ip
   ...
   }

关于variables - 在 Terraform 中,我可以选择是否根据不同的变量来寻址变量吗?网卡,动态静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64880190/

相关文章:

Java Switch语句困惑

javascript - 定义的 Var 不回显值 jquery 和 php

azure-devops - terraform 提供程序导致 TypeError : Cannot read property 'match' of null

azure - 属性值不适当 "network_interface_id": string required

azure - Terraform:错误:解析应用服务资源 ID 时出错

PHP - 使用数组外部数组中的值

php - 徽章系统和存储条件作为变量?

terraform - Terraform (Hashicorp) 的不同环境

terraform - Vault - 为一个身份组分配多个别名

terraform - 此处不能使用each.value