Terraform可以根据Azure订阅选择要使用的操作系统映像吗?

nuypyhwy  于 2023-03-24  发布在  其他
关注(0)|答案(1)|浏览(92)

我正在为Terraform变量使用Map变量,如下所示。当我运行Terraform时,如果我当前的订阅是生产,我想选择prd_source_image_id,如果我当前的订阅是dev,我想选择dev_source_image_id。可以吗?
var.tf

variable "vm_template" {
  type = map(any)
  default = {
    vm1 = {
      prd_source_image_id = "prd_image"
      dev_source_image_id = "dev_image"
      }
   }
}

main.tf

resource "azurerm_linux_virtual_machine" "vm" {
  for_each = var.vm_template
...(omission)
  source_image_id     = each.value.source_image_id
...(omission)
}

您必须能够使用条件语句或正则表达式根据您的订阅选择操作系统映像ID。

mzaanser

mzaanser1#

您可以使用azurerm_client_configlookup function数据源:

variable "vm_template" {
      type = map(any)
      default = {
        vm1 = {
          prd_source_image_id = "prd_image"
          dev_source_image_id = "dev_image"
          default_image       = "default_image"
          }
      }
    }

    variable "subscriptions_to_env" {
      type = map(string)
      default = {
        "aaa-111-555-etc" = "dev",
        "111-aaa-999-etc" = "prd"
      }
    }

    data "azurerm_client_config" "current" {}

    locals {
      current_env = lookup(var.subscriptions_to_env, data.azurerm_client_config.current.subscription_id, "None")
    }

    resource "azurerm_linux_virtual_machine" "vm" {
      for_each = var.vm_template
    ...(omission)
      source_image_id     = local.current_env == "dev" ? each.value.dev_source_image_id : (
                              local.current_env == "prd" ? each.value.prd_source_image_id : each.value.default_image
                              )
    ...(omission)
    }

注:建议使用默认镜像(prd、dev或其他),条件如下:

If env is dev: image dev
else if env is prd: image prd
else image default

如果对你有帮助就告诉我

相关问题