如何在 Terraform 的 virtual_machine 资源中使用 shared_image 计划数据,如发布者、报价和 sku

How to use shared_image plan data like publisher, offer and sku in virtual_machine resource in Terraform

使用 Terraform v0.12.9,azurerm 提供程序 v1.36.1

场景:

如何在不硬编码的情况下从共享图像中获取计划信息?

好吧,我想只使用数据源检索数据:

data "azurerm_shared_image" "image" {
  name                = var.image_name
  gallery_name        = var.gallery_name
  resource_group_name = var.rsg_name
}

并在 virtual_machine 资源中使用必要的块,如下所示:

  storage_image_reference {
    id = data.azurerm_shared_image.image.id
  }

  plan {
    name      = data.azurerm_shared_image.image.sku
    publisher = data.azurerm_shared_image.image.publisher
    product   = data.azurerm_shared_image.image.offer
  }

但是,我收到一条错误消息:

Error: Unsupported attribute
This object has no argument, nested block, or exported attribute named "sku".

对于每个 sku、发布者和报价。

我们可以更好地了解我们正在处理的内容,以添加用于测试目的的输出,如下所示:

output "imagedata" {
  value = data.azurerm_shared_image.image
}

我们得到一个重要的见解:

imagedata = {
  "description" = ""
  "eula" = ""
  "gallery_name" = [removed]
  "id" = [removed]
  "identifier" = [
    {
      "offer" = "cis-centos-7-l1"
      "publisher" = "center-for-internet-security-inc"
      "sku" = "cis-centos75-l1"
    },
  ]
  "location" = [removed]
  "name" = [removed]
  "os_type" = "Linux"
  "privacy_statement_uri" = ""
  "release_note_uri" = ""
  "resource_group_name" = [removed]
  "tags" = {}
}

啊,现在使用 data.azurerm_shared_image.image.identifier.sku 也不会只在这里工作。就 Terraform 而言,标识符块是 数组中的一个元素

解决方案:

我们仍然以同样的方式检索数据:

data "azurerm_shared_image" "image" {
  name                = var.image_name
  gallery_name        = var.gallery_name
  resource_group_name = var.rsg_name
}

我们在 virtual_machine 资源中引用它,如下所示:

  storage_image_reference {
    id = data.azurerm_shared_image.image.id
  }

  plan {
    name      = data.azurerm_shared_image.image.identifier[0].sku
    publisher = data.azurerm_shared_image.image.identifier[0].publisher
    product   = data.azurerm_shared_image.image.identifier[0].offer
  }