首页 > 解决方案 > Terraform 使用“for_each”创建多个网络接口并引用“azurerm_public_ip”

问题描述

我有以下代码:

resource "azurerm_public_ip" "imaged_pub_ip" {
  for_each = var.create_vm_images ? var.vms_to_image : {}
  name                = "${var.team_name}_${var.release}_imaged_public_ip_${each.value}"
  location            = var.loc
  resource_group_name = "${var.team_name}_${var.release}_${var.owner}_${var.intention}"
  allocation_method   = "Static"

  tags = {
    team = var.team_name
    environment = var.env_name
    useby = var.useby
    release = var.release
    devops_work_item_id = var.devops_work_item_id
    owner = var.owner
    intention = var.intention
  }
}
resource "azurerm_network_interface" "imaged_net_int" {
  for_each = var.create_vm_images ? var.vms_to_image : {}
  name                = "${var.team_name}_${var.release}_imaged_net_int_${each.value}"
  location            = var.loc
  resource_group_name = "${var.team_name}_${var.release}_${var.owner}_${var.intention}"

  ip_configuration {
    name                          = "eth0"
    private_ip_address_allocation = "Dynamic"
    subnet_id                     = data.azurerm_subnet.subnet.id
    public_ip_address_id          = values(azurerm_public_ip.imaged_pub_ip).*.id
  }

我无法引用azurerm_public_ip.idin public_ip_address_id。它有一个错误:Inappropriate value for attribute "public_ip_address_id": string required.

我使用值映射来说明需要多少个实例:

variable "vms_to_image" {
  type = map
}
  create_vm_images = "true"
  vms_to_image = {
    vm_id1 = "1"
    vm_id2 = "0"
  }

我如何引用azurerm_public_ip.idfor public_ip_address_id

标签: terraform

解决方案


这有效public_ip_address_id = azurerm_public_ip.imaged_pub_ip[each.key].id


推荐阅读